Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Constructor error

Status
Not open for further replies.

daveask

Programmer
Aug 11, 2004
108
GB
Hi Experts,

Why such a simple code got an error:

class MyClass
{
protected:
int itsValue;
public:
MyClass(int value){itsValue = value;}
};

class InhClass : public MyClass
{
public:
InhClass();
};

void main()
{
InhClass class2;
}
 
The error you get probably gives a hint.

The code above doesn't implement the InhClass constructor anywhere.

And even if it did, MyClass doesn't have a default constructor for InhClass' to call.

>Why such a simple code got an error

Code doesn't have to complex to be wrong.

/Per

"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."
 
PerFnurt,

Thank you for your help!

>Code doesn't have to complex to be wrong
Haha....I know...

>MyClass doesn't have a default constructor for InhClass' to call.
That is what I don't know: I got a constructor already in my code....what you mean by default constructor? Is that necessary for inheritance class?
 
You declare a constructor for InhClass but do not implement it. Also, when you create an InhClass object, it calls the base class's constructor before it calls InhClass's constructor. MyClass has no constructor which does not take parameters, so it doesn't know what to do. Here's how to fix your code:

Code:
class MyClass
{
protected:
     int itsValue;
public:
     MyClass(int value){itsValue = value;}
};

class InhClass : public MyClass
{
public:
     InhClass() : 
       MyClass(0) // Call MyClass's constructor and set itsValue to 0 
     {
     }
};

int main()
{
     InhClass class2;
     return 0;
}

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top