why doesn't this work?

L

Luck

struct Base
{
Base() : i(0){}
int i;
};

struct Derived : public Base
{
Derived() : i(1){}
};
 
V

Victor Bazarov

Luck said:
struct Base
{
Base() : i(0){}
int i;
};

struct Derived : public Base
{
Derived() : i(1){}
};

You're only allowed to initialise classes own bases and members.
Exception is a virtual base class, but yours is not the case.

If you need to initialise 'i' in derived, you need to give Base
a parameterised constructor:

struct Base
{
Base(int i_ = 0) : i(i_) {}
int i;
};

struct Derived : public Base
{
Derived() : Base(1) {}
};

Notice how I kept 'Base's constructor "default" by giving its 'i_'
the default value of 0. Essentially it's the same as your Base().

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,199
Messages
2,571,045
Members
47,643
Latest member
ashutoshjha_1101

Latest Threads

Top