As you have seen in the title i need to find the error in the code bellow, Here is what i know:
What i don't know is:
Here is the code:
#include <iostream>
using namespace std;
class A
{
protected:
int i;
public:
A(int i) :i (i) {}
};
struct B : A
{
B() {}
void set(int i) { this-> i = i; }
void print() { cout << i << endl; }
};
int main()
{
B b; b.set(2);
b.print();
}
I think your title is misleading, but the question is valid.
In order to construct B, A needs to be constructed as well (that you know)
but how can A be constructed without knowing the value of int i
in its constructor?
But you could use the parameter-less constructor of B to provide value for i
:
struct B : public A {
public:
B(): A(53 /* value for int i */) { }
...
but unless you specify what constructor of A should B use, the compiler will search for the default constructor (which does not exist in A`s case)