Click here to Skip to main content
15,347,207 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
#include<iostream>
#include<string>
using namespace std;
class father
{
int height;
public:
father(int h)
{
height=h;
cout<<"i am in father class"<<endl;
cout<<"height of my child is "<<height<<" feet"<<endl;
}
};
class child : protected father
{
public:
child(int x) : father(x)
{
cout<<"i am in child class";
}


};
int main()
{
child ajit(6);
}

What I have tried:

#include<iostream>
#include<string>
using namespace std;
class father
{
int height;
public:
father(int h)
{
height=h;
cout<<"i am in father class"<<endl;
cout<<"height of my child is "<<height<<" feet"<<endl;
}
};
class child : protected father
{
public:
child(int x) : father(x)
{
cout<<"i am in child class";
}


};
int main()
{
child ajit(6);
}
Posted
Updated 21-Mar-16 3:46am
Comments
Richard MacCutchan 21-Mar-16 9:04am
   
Very interesting, do you have a question?

There is no instance of the base class. There is only an instance of the derived class.

Because the member variables of the base class are part of the derived class (located in memory before the additional members of the derived class) they can be accessed by functions of the base class.

Once the memory for the class has been allocated, the constructor is executed which calls first the constructor of the parent class passing the pointer to the memory (the this pointer).

See also Initialization Lists in C++ - Cprogramming.com[^].
   
The "child" class constructor can't "pass a value" to it's "parent" class constructor: the syntax of the parameterised constructor just seems to imply that.
C++
child(int x) : father(x)

What it actual does is call the "parent" constructor with the parameter value before the "child" constructor begins to execute instead of calling the default parameterless "parent" constructor. It's just a way to allow you to correctly construct both classes from your code when you do this:
C++
child ajit(6);

Constructors cannot start executing until the base class constructor(s) are complete, or any calls to inherited methods could fail.
   
Comments
Member 12384360 21-Mar-16 16:03pm
   
i just want to know that at the starting of execution constructor of father class is executed and at that time a default value have to as output for variable height

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900