Moritz Göckel
Moritz Göckel

Reputation: 147

C++ Is it possible that the base class has a function with a parameter of the derived class

I want to do essentially the following:

class Base{
     void dosomestuff(Derived instanceOfDerived)
     {
         //Something
     }
};

class Derived : public Base{
     //Something
};

The Base needs a include of Derived, but to declare Derived it needs the declaration of Base first. Forward declaration does not work, because I do not want to use pointers.

Now my question: How do I accomplish that without pointers? Is that even possible? Or is the only possibility to make instanceOfDerived a pointer?

Upvotes: 0

Views: 81

Answers (3)

T.C.
T.C.

Reputation: 137320

The original version of the question asks about having Base hold Derived as a data member. That's obviously impossible. It's the same infinite recursion problem (a Derived contains a Base subobject, so a Base would recursively contain itself, and it will be turtles all the way down.)

The revised question asks about having a member function of Base taking a by-value argument of type Derived. That's perfectly possible. You need a forward declaration of Derived, and to defer the definition of the member function until after the actual definition of Derived:

class Derived;
class Base{
     void dosomestuff(Derived instanceOfDerived); // declaration only
};

class Derived : public Base{
     //Something
};

// out-of-class definition, so making it explicitly inline
// to match the in-class definition semantics
inline void Base::dosomestuff(Derived instanceOfDerived) {
     //Something
}

Demo.

Upvotes: 3

W.F.
W.F.

Reputation: 13988

You better do something like:

class Derived;
class Base{
     void dosomestuff(Derived& instanceOfDerived)
     {
         //Something
     }
};

class Derived : public Base{
     //Something
};

I would even move the body of method dosomestuff to the source cpp code where you can include derived.h as well as base.h

base.h could look like:

#ifndef BASE_H_
#define BASE_H_

class Derived;
class Base{
     void dosomestuff(const Derived& instanceOfDerived);
};

#endif

derived.h:

#ifndef DERIVED_H_
#define DERIVED_H_

#include "base.h"

class Derived : public Base{
     //Something
};

#endif

base.cpp:

#include "base.h"
#include "derived.h"

void Base::dosomestuff(const Derived &instanceOfDerived) {
    //Something
}

Upvotes: 3

ybdesire
ybdesire

Reputation: 1683

That means your inheritance model is not make sense if you really want to do that. Remember "Make sure public inheritance models 'is a.' "http://debian.fmi.uni-sofia.bg/~mrpaff/Effective%20C++/EC/EI35_FR.HTM If you make them have inheritance relationship, that means Derived is a Base, instead of "Derived is part of Base". You can create 2 classes to do that instead of making them have inheritance relationship.

Upvotes: 0

Related Questions