Search code examples
c++inheritanceconstructorpublic

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


#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?


Solution

  • 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.