Passing parameter to base class constructor

Started by
3 comments, last by Zahlman 17 years, 8 months ago
I'm trying to pass a parameter to a base class's constructor but my compiler is complaining that it can't find the base class constructor. Below is a basic example of what I'm trying to do. I've omitted the implementation of the constructors.


class Parent
{
    public:
        Parent(int);
};

class Child : public Parent
{
    public:
        Child(int);
};  

int main()
{
    Parent* pChild = new Child(42);
}


The compiler is looking for Parent() rather than Parent(int). If I create the Parent() constructor it compiles but the parameter never makes it to the base class constuctor. Is it possible to sent a parameter to a base class constructor? Thanks, Eugenek
Advertisement
So, you want us to tell you what you did wrong in your constructors, but you think it's okay to omit the implementation of said constructors? Remember, if you have a bug you don't understand, you probably aren't able to reasonably pass judgement on what portions of the code are relevant and which are not. Consequently, you should err on the side of caution and post more code rather than less.

To invoke a base class constructor from a derived class, you call the constructor from the member initialization list of the derived class, as follows:

class Parent{    public:        Parent(int)        {           /* whatever... */        }};class Child : public Parent{    public:        Child(int a)        : Parent(a)        {        }};  int main(){    Parent* pChild = new Child(42);}


Note that since you (probably) did not do that in your original code, the compiler tried to default-construct the base portion of the child object, which it could not do since you suppressed generation of the default Parent constructor by provided a parameterized version.
I think this part is what you were looking for:
  Child(int a)        : Parent(a)        {        }

You have to explicitly call the non-default constructor in the derived class's constructor(s).

Greetz,

Illco
Thanks. That did the trick.

I apologize for not including the implementation of the constructors. They were trivial to me since they could simply just "cout" the parameter for my demostration purposes. However, I should have including them nevertheless so it could be seen that I wasn't doing what I should have been doing.

Thanks again.
For future reference: it is usual to try to trim one's problem down to a *minimum, complete* code sample that reproduces the problem. So for example, if a problem with constructors doesn't depend on the constructor contents, then you would confirm that the problem is reproduced with empty constructors, and post a code sample with empty contructors (here you could just put {}'s instead of the ;'s). [smile]

This topic is closed to new replies.

Advertisement