0

I am working on a code where I need to pass the object of derived(child) class as a parameter into a function of base(Parent) class. I have studied lot of questions already asked, but all of them are giving the solution using pointers. (Some of them are following)

Passing derived class to base function

Passing object of derived class to base class

cast a pointer to member function in derived class to a pointer to abstract member function

Base Class reference to Pointer of Derived Class

But I wanted to ask if there is any way to do this without using the pointers or references. Here is my code. Kindly guide me in the above-mentioned context.

class parent;
class child;

class parent{
    public:
        void demo(child c)
        {
            cout<<"Parent"<<endl;           
        }   
};

class child:public parent{
    public:
        void demoChild()
        {
            cout<<"Child"<<endl;
        }
};

int main()
{
    parent p;
    child c;
    p.demo(c);
    c.demo(c);
    
    return 0;
}
  • 1
    What's the goal? Passing by value, as you do now, will cause cyclic dependency, since the base class has to know the derived class (because of the function signature) and the derived class the base (since it inherits from it). – Mikael H Jun 23 '20 at 12:22
  • Usually, the base class should not know about its derived classes, only the derived classes of the base class. – Mikael H Jun 23 '20 at 12:22
  • You can't pass an instance of a derived class to a function expecting to be passed a base value, unless you want object slicing (which loses all attributes specific to the derived class). You can pass an instance of the derived class by either a pointer (pass the address) or a reference. That (mostly) only makes sense if the base class is polymorphic - which yours is not. – Peter Jun 23 '20 at 12:36
  • @Peter I don't think there is any _function expecting to be passed a **base value**_. Their function passes a _**derived value**_ instead. – Daniel Langr Jun 23 '20 at 12:38

1 Answers1

1

A passed-by-value parameter in a function definition cannot be an incomplete type. You need to just delcare demo member function inside the class and define it at some place where child is a complete type already:

class parent;
class child;

class parent
{
  public:
    void demo(child c); // incomplete type allowed in declaration
};

class child : public parent
{
  public:
    void demoChild()
    {
      std::cout << "Child" << std::endl;
    }
};

void parent::demo(child c) // child is a complete type here
{
  std::cout << "Parent" << std::endl;           
}   

Live demo: https://godbolt.org/z/7MNMC3


Anyway, if your code is not just for learning purposes, I would guess that this is an XY problem.

Daniel Langr
  • 22,196
  • 3
  • 50
  • 93