Hash include
Hash include

Reputation: 23

Compiler error in my inheritance code in C++

I was learning about inheritance in C++. So whenever a object of a class is created a constructor is called. And constructor is used to initialize the class variables.

#include<bits/stdc++.h>
using namespace std;
class Base
{
    protected:
        int x;
    public:
        
        Base(int a): x(a)
        {
            cout<<"Base"<<endl;
        }
};
class Derived: public Base
{
    private:
        int y;
    public:
                                      
        Derived(int b):y(b)
        {
            cout<<"Derived"<<endl;
        }
    
        void print()
        {
            cout<<x<<" "<<y<<endl;
        }
};
int main()
{
    Derived d(20);
    d.print();
    return 0;
}

Since here I am creating object of base class and calling print function on this. So I should get output. But my code is giving compiler error, why? Can anyone help me understanding this?

Upvotes: 1

Views: 188

Answers (1)

rawrex
rawrex

Reputation: 4064

When you construct your Derived object in the Derived(int b): y(b) {}, the Base part of this object has to be constructed too. Since you do provide a constructor for Base which takes an int there won't be an implicitly defined default constructor in the Base (even if it was, the int data member x would have an undefined value). Thus, there's no way to construct the d in the Derived d(20) using your definitions for both classes.

You may look toward the following approach:

// Inside Base class:
// We provide a default constructor
// As well as one that takes an int
Base(int a = 0): x(a) {} 

// Inside Derived class:
// We supply a value for the Base and a value for the Derived part
Derived(int b, int d): Base(b), y(d) {} 

// Inside main():
Derived d(20, 30);
d.print();
// Prints: 20 30

When we have a default constructor provided for the Base, we can even do like so, and it will compile:

// Base part will be default constructed
Derived(int b): y(b) {} 
// ...Prints: 0 20

Here, the Base part of a Derived instance will have a default value, while the Derived part will have a value explicitly supplied to it. In general, this would probably be a mistake, of logical nature. Nevertheless, it will compile.

Upvotes: 5

Related Questions