Question

I have 1 base class and a couple of derrived classes that are pretty identic to the base. They look kind of like that:

class Base
{
protected:
    data stuff;
    size_t length;
public:
    Base();
    ~Base();
    virtual void print() 
    {
       std::cout << "Base" << std::endl;
    }
    // Some more virtual functions
};

class Der1: public Base
{
public:
    void print()
    {
       std::cout << "Der1" << std::endl;
       Base::print();
    }
};

class Der2: public Base
{
public:
    void print()
    {
       std::cout << "Der2" << std::endl;
       Base::print();
    }
};

This example is kind of stupid, but what I want to say is that derived classes don't really affect the data itself - only 1 method that does something before actually printing data.

The problem I have is that I have some functions that get Base class as a parameter and does something with the data. The problem is - I can pass derived classes to those functions, but they are passes as Base class - so they lose their overloaded print, and if printed from inside of such function - it won't print any "Der1" or "Der2" strings to stdout.

Edit: They are passed as (const Base &source)

So my question is - what is a way to properly pass derived classes to such functions?

Was it helpful?

Solution

It looks like your functions get Base class as the parameter by value. If you use passing by reference instead - so function(Base& object) instead of function(Base object) - nothing will be lost.

OTHER TIPS

In addition to previous answer, please see below your example:

#include <iostream>

class Base
{protected:
int stuff;
size_t length;
public:
Base(){};
~Base(){};
virtual void print()
{std::cout << "Base" << std::endl;}
// Some more virtual functions
};

class Der1: public Base
{public:
Der1(){};
~Der1(){};
void print()
{
   std::cout << "Der1" << std::endl;
   Base::print();
};
};
class Der2: public Base
{public:
void print()
{
   std::cout << "Der2" << std::endl;
   Base::print();
};
};

void function(Base& base)
{
  base.print();
}

int main(void)
{
 Der1 derived;
 function(derived);
 return 0;
}

Execution: Der1 Base

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top