c++ Is it possible to derive a class from base class that is already created.

Started by
7 comments, last by chadsxe 14 years, 5 months ago
class A class B : public A A a; B b; This would essentialy create two objects of Class A correct? Is it possible to only have one instance of A even though b is derived from A? Regards Chad
Advertisement
No.
Quote:Original post by SiCrane
No.


Just to be clear that is yes to the first question and no to the second correct.

Regards

Chad
Yes. Make an instance of A, once.
[size="2"]I like the Walrus best.
Ok I am confused...

What happens if multiple classes inherit from one common base class

class A
class B : A
class C : A

Does this mean when

B b;
C c;

there are two instances of A.

Regards

CHad
There are instances of C and B which both inherit from A.

They are not A because:

- They might declare properties and methods 'A' doesn't have.
- 'A' may have properties and methods that are not accesible from it's derived classes.
[size="2"]I like the Walrus best.
Quote:Original post by chadsxe
Ok I am confused...

What happens if multiple classes inherit from one common base class

class A
class B : A
class C : A

Does this mean when

B b;
C c;

there are two instances of A.

Regards

CHad


No, there's an instance of B and an instance of C, both of which contain data defined in A. Creating a new instance of a class allocates a new set of data. A derived class will also have a new instance of its base class's data allocated.

If you allocate C 3 times, you'll have 3 instances of C in memory, which will contain all of C's data (which includes A's data, per its definition). If you allocate a B and a C, then you'll have an instance of B's data (which includes A's data per its definition) and an instance of C's data (which includes A's data).

It seems that you're confusing class definitions with instantiated objects.
what you want is static members and functions in A that all b's inherit, then in effect there is only one A. Otherwise instead of deriving from A have b's have a static A as a member.
Just figured it out.

Thanks to all.

Regards

Chad

This topic is closed to new replies.

Advertisement