Base/Subclass constructor problems :(

Hello anyone who dares to read this,
I'm studying inheritance in c++ and there's one particular issue i'm having trouble with. I've wrote this small piece of code with a base and subclass that share an integer value. The subclass has an overriding function that simply adds 5 to whatever value is passed to the integer. The problem i'm having is that when I create an object of the subclass, I have to include a value when it's initialized. I've tried creating default constructors to automatically set the integer value, but they don't seem to be working. If anyone could point me in the right direction it would be much appreciated.
- thanks-
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using namespace std;
#include <iostream>
#include <string>
class base
{
protected:
	int num;
public:
	base()
	{
		num = 7;
	}
	base(int number)
	{
		num = number;
	}
	int get_num()
	{
		return num;
	}
};



class subclass : public base
{
public:
	subclass() :base(){}
	subclass(int new_num) :base(new_num){}
	int get_num()
	{
		return num + 5;
	}
};

int main()
{
	subclass A(5);
	subclass B(); // goal for me is to have the default constructor work
	cout << A.get_num();
	cout << B.get_num(); //PROBLEM

}
If you want to use class default constructor, replace line 39 with
subclass B;
No need for the bracket.
Also, when you override the function, make sure you put keyword "virtual" in front of the base class's function declaration
1
2
3
4
virtual int get_num()
	{
		return num;
	}

Otherwise the duplicate implementation will be simply hidden in stead of overwritten
Thanks you very much for the speedy reply, I had no idea about the virtual keyword, thanks alot!
Topic archived. No new replies allowed.