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-
usingnamespace 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
virtualint get_num()
{
return num;
}
Otherwise the duplicate implementation will be simply hidden in stead of overwritten