How can I set up my class so it won't be inherited from?

V

Victor Bazarov

Nikolay said:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.11offers
a solution of the problem:

class Fred;

class FredBase {
private:
friend class Fred;
FredBase() { }
};

class Fred : private virtual FredBase {
public:
...
};


The only thing I want to know is why did he make FredBase a virtual
base. It works even if inheritance is non-virtual. Why virtual
inheritance is better??

How does it work if the inheritance non-virtual? What error does
your compiler report here:

class Fred;

class FredBase {
private:
friend class Fred;
FredBase() { }
};

class Fred : private /*virtual*/ FredBase {
};

class Foo : public Fred {};

class Bar : private Fred {};

int main() {
Foo foo;
Bar bar;
}

I've derived TWO classes from Fred and my compiler had no problem
letting me.

V
 
N

Nikolay Kurtov

I've derived TWO classes from Fred and my compiler had no problem
letting me.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask- Hide quoted text -

- Show quoted text -

Sorry, it really produces an error.
Now I really confused and cannot understand why it is possible to
derive.
Isn't it true, that a usual inheritance runs first constructor of the
base class and then of the derived one?
 
N

Nikolay Kurtov

Sorry, it really produces an error.
I meant without "virtual" it IS possible to derive from Fred.
 
V

Victor Bazarov

Nikolay said:
Sorry, it really produces an error.

Who "it"? What error?
Now I really confused and cannot understand why it is possible to
derive.

It's possible to derive from _my_ Fred (that doesn't have 'FredBase'
as virtual base class) because NOTHING prevents you from that.
Isn't it true, that a usual inheritance runs first constructor of the
base class and then of the derived one?

The virtual base class subobject is supposed to be _initialised_ in
the most derived class' constructor. If you derive from [the original]
'Fred', say a class 'Foo', then 'Foo::Foo' is responsible for
initialising the 'FredBase' (even if it happens implicitly), and since
'FredBase's constructor is private, it's not accessible to 'Foo' (or
any other class derived from 'Fred' for that matter). That's why you
cannot derive from 'Fred' given in the FAQ. The inability to initialise
the virtual base class in any derived from 'Fred' class makes 'Fred'
non-derivable.

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
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top