How to make a Derived Base Dependent?

I have a class Base (abstract, with pure virtual) and Derived (which inherit Base). I use this:
 
Base* A = new Derived();

But I can do this:
 
Derived A;


How make Derived dependent of Base in one file?
Not sure I understand what you're getting at. If Derived is Derived from Base, then it will always be dependent on Base.

The second example you give there:
 
Derived A;


Nothing is special about this one, other than the object is not generated dynamically.


If you mean you want to forbid creating Derived objects on the stack (why?) then you can do the following:

1) Make the Derived ctor(s) private
2) Make a static 'create' function which returns a Base pointer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Derived : public Base
{
private:
    Derived();  // make ctors private

public:
    static Base* create()
    {
        return new Derived;
    }
};

//...

int main()
{
    Derived A;  // <- error, ctor is private

    Base* foo = Derived::create();  // <- ok 


But I don't see the advantage to this. Why not just allow the user to create normal Derived objects?
Ok. Let's think on Qt: QLabel *A = new QLabel(this);. The "this" paramter is a QObject*. But why? How? I program in C++ since 2011 and I never used polymorphic pointers.
Inheritance forms an "is a" relationship.

For example... if Poodle is derived from Dog, it implies that a Poodle is a Dog:

1
2
3
4
5
6
7
8
9
class Dog
{
  //...
};

class Poodle : public Dog
{
  //...
};



Generally the way it works is that base classes are more generic, whereas derived classes get more and more specific the further down the hierarchy you go. Like in this example, we have a generic 'Dog' class... and a more specific 'Poodle' class.

The idea is that actions that are common to ALL dogs can be placed in the generic Dog base class... whereas actions that are specific to Poodles go in the more specific sub class.


C++ facilitates this by allowing a pointer to a derived type to be automatically cast to a pointer to a base type:

1
2
3
4
5
6
Poodle fluffy;  // fluffy is our poodle.

Poodle*  ptr_fluffy = &fluffy;  // ptr_fluffy points to our fluffy poodle
Dog* ptr_dog = ptr_fluffy;  // <- this is also OK.  ptr_fluffy
     // points to a Poodle... which means it ALSO points to a Dog... because
     //  a Poodle "is a" Dog. 



Coming back to your Qt example:

QLabel *A = new QLabel(this);

This code will work as long as whatever class you're in (ie: the class the 'this' pointer points to) is derived from QObject. Any derived class will work. If a class such as QWindow is derived from QObject, then a pointer to a QWindow is also a pointer to a QObject.... since a QWindow "is a" QObject.
Thanks. Solved :).
Topic archived. No new replies allowed.