a code about inheritance

hi:
I have a code below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

#include<iostream>
using namespace std;

class A{

   int x;
public:
	A(int a):x(a){cout << "constructing A" << endl;}

};

class B:public A{

public:
	B(){cout << "constructing B" <<endl;}

};

int main()
{

   B b;
}


when I complie it ,the compile have a error:
error C2512: 'A' : no appropriate default constructor available.
I just only define a class B object and not base class A.why I have a error about it?
Because B has to construct A's data members by calling A's constructor. Since you explicitly defined your own constructor for A and didn't define the deafult one, the default one doesn't exist, so B can't call it. I think there was a way to call the base class's constructor but I forget how - anyway, just define
A():x(0){cout<<"constructing A (default constructor)"<<endl;}
Last edited on
I think there was a way to call the base class's constructor but I forget how


With an initializer list:

 
B() : A(5) { cout << "constructing B" << endl; }
Topic archived. No new replies allowed.