Jimit Rupani
Jimit Rupani

Reputation: 510

How to Institiate an object in when we have pure virtual function hirerachy?

class A{
    public: virtual void getName() = 0;
};

class B: public A{
    public:
        B(int a){
            cout<< "B Name : " << a <<endl;
        }
        void getName() override { cout << "Class B" << endl; }
};

class C: public B{
    public:
      C(int a){
            cout<< "C Name : " << a <<endl;
        }
        void getName() override { cout << "Class C" << endl; }
};

int main()
{
    B *b = new B(10);
    b->getName();

    C *c = new C(20);
    c->getName();
}

I am trying to create the object of Class B and C.but it gives me that error of

main.cpp:31:15: error: no matching function for call to ‘B::B()’
       C(int a){
               ^
main.cpp:22:9: note: candidate: B::B(int)
         B(int a){
         ^ 

can anyone explain to me why is that happening? why it is not creating the class object?

Upvotes: 3

Views: 90

Answers (3)

Some programmer dude
Some programmer dude

Reputation: 409356

The problem doesn't have anything to do with the abstractness of any parent class, it's because your C constructor tries to initialize the parent B class through the B default constructor, which it doesn't have any.

You need to "call" the parameterized B constructor through the constructor initializer list

C(int a)
    : B(a)  // "Calls" the B constructor
{
}

Optionally add a default constructor to the B class.

Upvotes: 2

Gaurav Sehgal
Gaurav Sehgal

Reputation: 7542

B(int a){
        cout<< "B Name : " << a <<endl;
    }

When you construct C, B also needs to be constructed. If you do not specify how to intialize sub class (through initializer list specifying the constructor to be called), base is default constructed which requires a default constructor.

Since you defined a constructor for B class, there is no default constructor generated for B. You could either define a default constructor for B or specify B(int a) to be used through initializer list.

Note that you could create object of B without specifying constructor for base A since A class has a default constructor generated which is used.

Upvotes: 2

songyuanyao
songyuanyao

Reputation: 172964

This issue has nothing to do with virtual functions.

You have to specify which constructor of B should be used to initialize the base subobject B in member initializer list explicitly, otherwise, the default constructor of B would be used but B doesn't have one. (Note that B has a user-defined constructor taking int then default constructor won't be generated for B.)

For members that cannot be default-initialized, such as members of reference and const-qualified types, member initializers must be specified.

e.g.

C(int a) : B(a) {
//       ^^^^^^
    cout<< "C Name : " << a <<endl;
}

Upvotes: 6

Related Questions