Calling Derived Class Function from Base Class

Calling derived class function from base class

The code you've posted should work the way you want. Calling doSomething on an instance of derived will call the overridden start and stop functions defined in derived.

There's an exception to that, though. If you call doSomething in the constructor or destructor of base (whether directly or indirectly), then the versions of start and stop that get called will be the ones defined in base. That's because in those circumstances, you don't actually have a valid derived instance yet. It's either not fully constructed or partially destructed, so the language prevents you from calling methods that would use the partial object.

If you're not calling it from a base constructor or destructor, then there is more to the problem than what's shown here.

Call derived class' function from a base class' instance

  Derived d;
d.test();
Base b;
b = d;
b.test(); // why called Base::test() ?

You created a Derived object d and Base object b. And later assigned b=d; Here object slicing is happening. After the assignment b has only Base part of the Derived class info in hand. So when you call b.test() it will call Base::test() instead Derived::test() function.

  Base* b1 = new Derived();
b1->test();
delete b1;

Here you dynamically created a Derived class object in heap and returned the pointer of that object to Base class pointer. Here pointer is nothing but the memory address holding the Derived class object. And when you call b->test(), system internally identify the type of the object dynamically and it is returned as Derived. So it will call Derived::test() function.

How to call a parent class function from derived class function?

I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private).

If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...). You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super or base) since C++ supports multiple inheritance which may lead to ambiguity.

class left {
public:
void foo();
};

class right {
public:
void foo();
};

class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();

// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};

Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.

class bottom : public left, public left { // Illegal
};

How do I call a derived class method from the base class?

The correct way is to add a method DoSomeMagic() in the base class,
with default implementation, or abstract.
The derived class should than override it to do its magic.

Something like this maybe:

public class WireLessDevice
{ // base class
protected virtual void ParseMessage()
{
// Do common stuff in here
}
}

public class WiFi : WireLessDevice
{ // derived class
override void ParseMessage()
{
base.ParseMessage();//Call this if you need some operations from base impl.
DoGPSStuff();
}
private void DoGPSStuff()
{
//some gps stuff
}
GPSLoc Loc;
}

How to call derived class method from base class pointer?

You need to make DoSomething() a virtual function in both classes to get the polymorphic behavior you're after:

virtual void DoSomething(int i) { ...

You don't need to implement virtual functions in every sub class, as shown in the following example:

#include <iostream>

class A {
public:
virtual void print_me(void) {
std::cout << "I'm A" << std::endl;
}

virtual ~A() {}
};

class B : public A {
public:
virtual void print_me(void) {
std::cout << "I'm B" << std::endl;
}
};

class C : public A {
};

int main() {

A a;
B b;
C c;

A* p = &a;
p->print_me();

p = &b;
p->print_me();

p = &c;
p->print_me();

return 0;
}

Output:

I'm A

I'm B

I'm A

Call derived class method from within base class?

Solution by OP.

public ref class BaseClass abstract
{
virtual void BaseClass::OverriddenMethod() abstract;

void BaseClass::Run()
{
// Do some initial work here.

// Call the derived class's version of OverridenMethod to do final work:
BaseClass::OverriddenMethod(); // DONT DO THIS!!!!!!!!
OverriddenMethod(); // DO THIS INSTEAD!!!!!
}
};

The issue here was because I was using a header for definitions and a cpp file for implementations of my base class. In the cpp file, I typically use ClassName::MemberName notation to refer to any of ClassName's members. However, doing so in this case forces the base class's virtual method to get called instead of the overridden method in the derived class.

This is why, when using the abstract keyword, I was getting the C3278 error when calling OverriddenMethod() inside of the Run() definition of the base class. Its because I was calling BaseClass::OverriddenMethod(), which points to nothing but an abstract definition.

Is there a way to call derived class functions with base class pointer without virtual

Since I could not get any answer from anyone, let me float an option here which I have thought of. This might be a hack though. I am open for correction/comments and criticism as well. :)

The deal is to do reinterpret_cast in the base class functions.

#include <iostream>
#include <vector>

bool preState = true;
class Derived;
class Base;

class Base {
public:
unsigned char a;
int b;
Base() : a('a'), b (2) { };
unsigned char get_a() const;
int get_b() const;
} __attribute__ ((__packed__)) ;

class __attribute__ ((__packed__)) Derived : public Base {
public:
unsigned char c;
int d;
Derived() : c('c'), d(4) { };

unsigned char get_a() const;
int get_b() const;
};

unsigned char Base::get_a() const {
if (preState) {
return a;
} else {
const Derived* d = reinterpret_cast<const Derived*>(this);
return d->get_a();
}
}

int Base::get_b() const {
if (preState) {
return b;
} else {
const Derived* d = reinterpret_cast<const Derived*>(this);
return d->get_b();
}
}

unsigned char Derived::get_a() const {
return c;
}

int Derived::get_b() const {
return d;
}

int main() {
std::vector<Base*> bArray;
bArray.push_back(new Base());
bArray.push_back(new Base());

std::vector<Base*>::iterator bArrayIt = bArray.begin();
for (; bArrayIt != bArray.end(); ++bArrayIt) {
std::cout << (*bArrayIt)->get_a() << " ";
std::cout << (*bArrayIt)->get_b() << std::endl;
}

preState = false;

std::vector<Base*> dArray;
bArrayIt = bArray.begin();
for (; bArrayIt != bArray.end(); ++bArrayIt) {
// Write copy constructor in Derived class which copies everything from
// base object to Derived object
Base* b = new Derived();
dArray.push_back(b);
}

std::vector<Base*>::iterator dArrayIt = dArray.begin();
for (; dArrayIt != dArray.end(); ++dArrayIt) {
std::cout << (*dArrayIt)->get_a() << " ";
std::cout << (*dArrayIt)->get_b() << std::endl;
}

}

The output of this would be:

a 2 // Base class get_a() and get_b()
a 2 // Base class get_a() and get_b()
c 4 // Derived class get_a() and get_b()
c 4 // Derived class get_a() and get_b()


Related Topics



Leave a reply



Submit