Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance in C++

Here's my problem: I have a virtual method defined in a .h file that I want to call in a class that inherits from the base class. Sadly though, the method in the derived class doesn't get called. Is there a better way to implement what I'm trying to do?

#ifndef ofxBASE_SND_OBJ
#define ofxBASE_SND_OBJ

#include "ofConstants.h"

class ofxBaseSndObj {

public:

    virtual string getType(){}

    string key;

};

#endif

Here's my buzz class

#ifndef OFXSO_BUZZ
#define OFXSO_BUZZ

#include "ofxBaseSndObj.h"

class ofxSOBuzz : public ofxBaseSndObj
{
public:
    string getType();
};

#endif

ofxSOBuzz.cpp

string ofxSOBuzz::getType()
{
    string s = string("ofxSOBuzz");
    printf(" ********* returning string type %s", s.c_str()); // doesn't get called!
    return s;
}

Then in another class I try to call it this way:

string ofxSndObj::createFilter(ofxBaseSndObj obj)
{
    string str = obj.getType();
    if(str.compare("ofxSOBuzz") == 0)
    {
        printf(" all is well ");
    }
}

In the method above I need to be able to pass in one of many kinds of objects that all extend the ofxBaseSndObj object. Any suggestsions or pointers would be greatly appreciated. Thanks!

like image 802
Joshua Noble Avatar asked Oct 25 '08 21:10

Joshua Noble


1 Answers

Change this line:

string ofxSndObj::createFilter(ofxBaseSndObj obj)

to

string ofxSndObj::createFilter(ofxBaseSndObj& obj)

What you are doing is passing by value (passing a copy).

This means you are copying the object to the function. Because the function does not know what type you are actually passing it only passes the type defined in the function declaration and thus it makes a copy of the base class (this is know as the slicing problem).

The solution is to pass by reference.

If you do not want the function to modify the object (maybe that is why you were passing by value so it could not alter the original) then pass a const reference.

class ofxBaseSndObj
{
    public:
        virtual string getType()  const;
        // If the method does not change the object mark it const

        string key;

};

string ofxSndObj::createFilter(ofxBaseSndObj const& obj)
{
    // allowed to call this if getType() is a const
    string str = obj.getType();

    if(str.compare("ofxSOBuzz") == 0)
    {
        printf(" all is well ");
    }
}
like image 186
Martin York Avatar answered Oct 13 '22 20:10

Martin York