Problem with C++ Constructor. What exactly is getting initialized here?

Viewed 130
#include<bits/stdc++.h>
using namespace std;


class Vehicle
{
private:
int speed;

public:
Vehicle(int x)
{
   speed=x;
   cout << "Vehicle's parametrized constructor called" << endl;
}
};

class Car : public Vehicle
{ 
   public:
   Car() : Vehicle(5)
   {
        cout << "Car's constructor called" << endl;
   }
};

int main()
{
    Car a;
}

Output- Vehicle's parametrized constructor called
Car's constructor called

Since the access specifier is public, speed is not inherited. What does 5 get assigned to as there is no speed member in Car?

3 Answers

Since the access specifier is public, speed is not inherited.

This is a misunderstanding. A derived class does inherit all members from the base class. What access specifier control is only whether the inherited class can access the members. The Car cannot directly access speed but the member is there.

Remember that public inheritance models a "is-a" relationship. A Car is a Vehicle. If Car didn't have the speed member it would not be a Vehicle.

You can use a display function to test that for yourself.

Add this function to your class Vehicle under public access specifier:

void display() { std::cout<<speed; }

Now from an object of derived class Car, call this function in main():

Car a; a.display();

It will output 5, which is the value of the variable speed you have initialzed in derived class Car, from base class Vehicle.

Since the access specifier is public, speed is not inherited.

Irrespective of access specifiers imposed, all variables are inherited. The difference is that they are not accessible directly. For private members like speed, you'll need to access them via a public member function, just like I did above.

What does 5 get assigned to as there is no speed member in Car?

It gets assigned to the derived variable speed in objects of Car.

Class Car is derived from Vehicle. when you create an object of class Car, it contains the memory for Vehicle also. it means object of class Car has Vehicle as a member. Hope this link will give a good understanding.

when you are creating an object of Car, it will call constructor of class Car which internally call constructor of class Vehicle before executing the body of Car constructor.

 Car() : Vehicle(5)

This is a way of initializing the members of Vehicle class. There is a concept of Initializer List in C++ and you can read here when it is better to use.

Value 5 is passed to Vehicle's constructor and eventually stored in class member speed .In your code if you print speed, you will see, whatever value you are passing is getting stored there.

Related