Search code examples
c++overridingabstract-class

How to execute overrided method C++


i'll try to create a structure for executing an overrided method in derived class. My base code structure:

Base.h EDITED

class Base 
{
protected:
    virtual void Initialize() = 0;
    virtual void Update() = 0;
public:
    void Init();
    void Upd();
};

Base.cpp

#include "Base.h"

void Base::Initialize() {}
void Base::Update() {}

void Base::Init() {
    // Some logic

    Initialize();
}

void Base::Upd() {
    // Some logic

    Update();
}

The following class is the class to be inherited from N other classes that implement Initialize() and Update() then:

Behaviour.h

#include <iostream>
#include "Base.h"

class Behaviour : public Base 
{
protected:
    virtual void Initialize();
    virtual void Update();
};

Behaviour.cpp

#include "Behaviour.h"

void Bheaviour::Initialize() {
    std::cout << "Initialize called!" << std::endl;
}

void Bheaviour::Update() {
    std::cout << "Update called!" << std::endl;
}

Then I want to execute Behaviour Initialize() and Update() when is executed in the Base class. My main function is:

Core.cpp EDITED

#include "Behaviour.h"

int main() {
    Base* base = new Behaviour();

    base->Init();
    while(!quit) {
        base->Upd();
    }
}

Thank's in advance for any suggestions!

Thanks for all suggestions, i've solved!


Solution

  • Change Base* base = new Base();

    to

    Base* base = new Bheviour;
    

    and polmorphism will take care of everything else. If you don't want to create an object out of base class better to declare it as an abstract class.