Sign in to follow this  

calling mother class constructors

This topic is 4813 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

you can pass along arguments via the initialization list. something like this:



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

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

Child ch(5);



sorry its really late and that might not be completely syntatically correct, but im guessing it will work.

Share this post


Link to post
Share on other sites
I'm not sure that that will help for what I'm trying to do. If I understand correctly the above code lets me pass parameters to the parent class via the child class. What I want to do is call a parent classes constructor form the child classes constructor.

Share this post


Link to post
Share on other sites
That code passes the parameters to the parents constructor (one constructor with parameters).

That's how to call the base class's constructors: by the initializer list.

If you don't explicitely call the parent class constructor the parents default constructor will be called by the compiler.

Share this post


Link to post
Share on other sites
The constructor of the parent class is called automatically after the constructor of the child class.

Try this in a console program:


#include <stdio.h>
#include <conio.h>

class A {
public:
A() {
printf("Start A\n");
}
~A() {
printf("Stop A\n");
}
};

class B : public A {
public:
B() {
printf("Start B\n");
}
~B() {
printf("Stop B\n");
}
};

int main(int argc, char *argv[]) {
A *myA = new A;
delete myA;

printf("------------\n");

B *myB = new B;
delete myB;

getch();

return 0;
}



The output should be:

Start A <- A's constructor
Stop A <- A's Destructor
-------
Start A <- A's constructor
Start B <- B's constructor
Stop B <- B's destructor
Stop A <- A's destructor

Share this post


Link to post
Share on other sites
Quote:
Original post by overflowed_
The constructor of the parent class is called automatically after the constructor of the child class.


I think you mean that the other way around (the parent class' default constructor is called automatically before the constructor of the child class) :-)

cheers
sam

Share this post


Link to post
Share on other sites

This topic is 4813 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this