0
class c_base_class {  
protected:
    . . .
public:
    void run( ) { 
        std::cout << "Error: Run called from base class! \n";
    };    

};

class c_derived_class : public c_base_class {
protected:
    . . .
public:
    void run( ) {
        std::cout << "Success: Run called from derived class \n";
    };    

class c_main {
protected:    
    std::vector<c_base_class*> listings;
public:
     void push_base( c_base_class* base ) { listings.push_back( base ); }; 

    void iterate ( ) {
        for ( auto listing : listings) {
            listing->run( );
        };
    };

    void run( ) {
        this->iterate( );
    };
}; extern c_main* g_main;
. . .

void some_stuff::run( ) {
    g_main->push_base( std::make_unique<c_derived_class>( . . . ).get( ) );
    g_main->run( ); // Iterator calls base class 'run' function instead of derived classes 'run' function.
};

Excuse any mistakes/errors. This was purely pseudo I wrote on here, I believe it's pretty understandable what I'm trying to achieve.

If not here's a way of interpreting this, there are multiple derived classes so having a vector of just that one would be useless. I want to call run from the derived classes while just pushing back the base class into the vector as shown in the code but however the iterator just calls the base classes run function.

alice
  • 33
  • 7

2 Answers2

2

Sounds as though you are wanting to make the function virtual? (i.e. it calls the version provided by the derived class, if available)

class c_base_class {  
protected:
    . . .
public:
    virtual void run( ) { 
        std::cout << "Error: Run called from base class! \n";
    }

};
robthebloke
  • 9,331
  • 9
  • 12
0

First, bugs.

g_main->push_base( std::make_unique<c_derived_class>( . . . ).get( ) );

In this line, the unique pointer will instantly deallocate the content. So you get a pointer to garbage in your code.

Change

...
std::vector<c_base_class*> listings;
...
g_main->push_base( std::make_unique<c_derived_class>( . . . ).get( ) );
...

to

...
std::vector<std::unique_ptr<c_base_class> > listings;
...
g_main->push_base( std::make_unique<c_derived_class>( . . . ));
...

aside from this. Base class function run() must be virtual. E.g.,

virtual void run( ) {...};

virtual indicates that during runtime the program needs to check which function to call. It attempts to calls the last derived class that implemented the function.

ALX23z
  • 4,456
  • 1
  • 11
  • 18
  • This works however I cannot iterate through `listings`. – alice May 15 '19 at 03:55
  • In the for loop replace `auto listing` with `auto&& listing`. (`auto a = b` makes `a` to be copy of `b`. In the case `auto&& a = b` here `a` is a universal reference to `b`. It is important because `std::unique_ptr` are non-copyable) @alice – ALX23z May 16 '19 at 04:22