user4757345 - 22 days ago 8

C++ Question

I have a

`base`

base.cpp:

`#include "base.h"`

base::base()

{

}

base::~base() {

}

void base::baseMethod(int a)

{

std::cout<<"base::baseMethod : "<<a<<std::endl;

}

base.h

`#ifndef BASE_H`

#define BASE_H

#include <iostream>

class base {

public:

base();

base(const base& orig);

virtual ~base();

void baseMethod(int);

private:

};

#endif /* BASE_H */

And I have

`derivative`

derivative.cpp

`#include "derivative.h"`

derivative::derivative() : base(){

}

derivative::~derivative() {

}

void derivative::baseMethod(int a)

{

std::cout<<"derivative::baseMethod : "<<a<<std::endl;

}

void derivative::derivativeMethod(int a)

{

baseMethod(a);

derivative::baseMethod(a);

}

derivative.h

`#ifndef DERIVATIVE_H`

#define DERIVATIVE_H

#include "base.h"

class derivative : public base{

public:

derivative();

derivative(const derivative& orig);

virtual ~derivative();

void derivativeMethod(int);

void baseMethod(int);

private:

};

#endif /* DERIVATIVE_H */

main.cpp

`derivative t;`

t.baseMethod(1);

t.derivativeMethod(2);

and output is :

`derivative::baseMethod : 1`

base::baseMethod : 2

base::baseMethod : 2

When I call baseMethod with derivative class object, actually I am using baseMethod of derivative class . But when I call derivetiveMethod, I am using baseMethod of base class. Why is that ? and how can I call baseMethod of derivative class ?

Thanks.

I am using

`Netbeans 8.2`

`Windows 7 x64`

`g++ 5.3.0 (mingw)`

Answer

You need to make `baseMethod`

`virtual`

in the base class:

`virtual void baseMethod(int);`

You *don't* need to "re-affirm" the `virtual`

ness in the child classes, but some folk do that for clarity. (That also includes the destructor in the child class).

Source (Stackoverflow)

Comments