Problem with constructor in derived class

Since my question was very complex, I simplified it. I'm having trouble deriving classes. Here's the code:

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
26
27
28
#include "std_lib_facilities.h" // includes C++ standard library stuff

class A
{
protected:
	A();
};

struct B : A
{
	B(int nn) : n(nn) { }
private:
	int n;
};

struct C : B
{
	C(int nn) : n(nn) { }
private:
	int n;
};

int main()
{
	B obj_b(5);
	C obj_c(4);
	keep_window_open();
}


I get this compile time error:

'B' : no appropriate default constructor available

So I added a default constructor in B. The source code looks like this now:

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
26
27
28
29
#include "std_lib_facilities.h" // includes C++ standard library stuff

class A
{
protected:
	A();
};

struct B : A
{
	B();
	B(int nn) : n(nn) { }
private:
	int n;
};

struct C : B
{
	C(int nn) : n(nn) { }
private:
	int n;
};

int main()
{
	B obj_b(5);
	C obj_c(6);
	keep_window_open();
}


And now I get a new compile time error:

error LNK2019: unresolved external symbol "protected: __thiscall A::A(void)" (??0A@@IAE@XZ) referenced in function "public: __thiscall B::B(int)" (??0B@@QAE@H@Z)

error LNK2019: unresolved external symbol "public: __thiscall B::B(void)" (??0B@@QAE@XZ) referenced in function "public: __thiscall C::C(int)" (??0C@@QAE@H@Z)
Last edited on
It seems that you haven't linked the library correctly, you'll need to put the library into your linker. How it's done on VS I have no idea.
I wonder why such guys as you do invent some problems instead of carefully copy and paste code from a book? Where did you see that Circle described in the book has the default constructor? What is the meaning of data members r in class Circle and class Smiley?
closed account (D80DSL3A)
The link errors come from not providing definitions for the constructors.
Try A(){} instead of A();. Likewise for B.

Your 1st error comes from not supplying a call to the B(int) ctor in the C(int) ctor.
Note that struct C has two data members named n, one of which is contained privately within the base class object B that is a part of C.

If you wish to supply values for both of the n's, try:
C(int nb, int nc) : B(nb), n(nc) { }
...or, very similarry as fun2code said, if "n" should inizialize both B and "n" var of class B with one parameter only, you can also try

C(int nn): B(nn), n(nn) { }

I hope, however, you didn't truely use "same name variable of parent class" into child class (I mean... in your basic example you use "int n" both in B and in C)... I think it can be quite confusing even if the parent var is inaccessible in child class becouse it is a private member of the parent class.
Last edited on
@fun2code
@Nobun

Thanks guys! I fixed the problem. I just had to add a definition to A's & B's constructor.
Topic archived. No new replies allowed.