Special attention must be paid when it comes to base classes having parameterized constructors. When we declare a base class that has a parameterized constructor, the parameters can not be passed through the child class object directly. In other words, a child class object can not pass arguments to its base class constructor. So how would you call the base class constructor then ? The answer is by declaring a child class parameterized constructor.
Look at the following code
class child : public base
{
public:
child(int b) : base(b)
{
cout<<"\nThe same argument can be used here as well "<
{
public:
child(int b) : base(b)
{
cout<<"\nThe same argument can be used here as well "<
void main()
{
child c(10);
}
{
child c(10);
}
Here is the output :
Calling Base Class Constructor with the value 10
The same argument can be used here as well 10
The same argument can be used here as well 10
This is how it worksThe base class has a constructor which has an int parameter named "a", when we declare an object of the child class, the value (10) is passed to the argument "b" of the child class. From here the statement "base(b)" passes the value of "b" to the parent class constructor where the value is copied to the argument "a". The base class constructor prints the value as needed. The same value if required can be used in the child class constructor as well.
The summary is "The child class constructor must pass all the required arguments to the base class constructor".
Let's see a more practical example
class vehicle
{
char vname[10],type[10];
public:
vehicle(char vnm[],char ty[])
{
strcpy(vname,vnm);
strcpy(type,ty);
}
{
char vname[10],type[10];
public:
vehicle(char vnm[],char ty[])
{
strcpy(vname,vnm);
strcpy(type,ty);
}
void show_veh() {
cout<<"\nVehicle Name : "<
cout<<"\nVehicle Name : "<
public:
car(char vnm[],char ty[],char mk[],int m) : vehicle (vnm,ty)
{
strcpy(make,mk);
model=m;
}
car(char vnm[],char ty[],char mk[],int m) : vehicle (vnm,ty)
{
strcpy(make,mk);
model=m;
}
void show_car()
{
show_veh();
cout<<"\nMake : "<
{
show_veh();
cout<<"\nMake : "<
void main()
{
car mycar("City","Sports","Honda",2011);
mycar.show_car();
}
{
car mycar("City","Sports","Honda",2011);
mycar.show_car();
}
As you can see there is a base class(vehicle) which has a parameterized constructor. There is another parameterized constructor in the child class (car). The child class has only two properties namely, make and model therefore its constructor should be interested only in initializing only these two properties but since the base class constructor will be the first one to be invoked it is the responsibility of the child class to provide the the parameters to the base class. Therefore the constructor of the child class has declared four arguments, 2 for itself and 2 for its base class.
0 comments:
Post a Comment