Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My virtual function wont work C++

I have edited this from my real code, so that it is a little easier to understand.

The base class:

class MWTypes
{
public:
    virtual long get() { return (0); }
};

The derived class: (There are going to be other classes like char, double etc etc . . .)

class TypeLong : public MWTypes
{
public:
    TypeLong(long& ref) : m_long(ref) {}
    ~TypeLong();

    long get() { return m_long; }
private:
    long& m_long;
};

and the storage class:

class RowSet
{
public:
    void addElememnt(MWTypes elem);
    MWTypes getElement();

    std::vector<MWTypes> getVector() { return m_row; }

private:
    std::vector<MWTypes> m_row; 
};

How it is called:

for (i = 0; i < NumCols; i++) // NumCols is 3 on this instance
{
    switch(CTypeArray[i]) // this is an int which identifies the type
{  
    case SQL_INTEGER:
    {
    long _long = 0;

    TypeLong longObj(_long);
    MWTypes *ptr = &longObj;

            // some SQL code goes here that changes the value of _long, 
            // there is no need to include it, so this will do.
    _long++;

            // I now want to save the data in a vector to be returned to the user.
    rowSet.addElememnt(*ptr);   

///////////////////////////////////////////////
// some code happens here that is irrelevant //
///////////////////////////////////////////////

// I now want to return the typr I have saved in the vector, 
// I THINK I am doing this right?
    MWTypes returned = rowSet.getElement();

    // lastly I want to get the value in the returned type
    long foo = returned.get();

///////////////////////////////////////////////
// some code happens here that is irrelevant //
///////////////////////////////////////////////

I think I am on the right lines here. The value of 'foo' is always 0. I have a feeling this could be the way Im storing in the vector, or it could be the base virtual function, as it always returns 0.

If I remove the return in my base class I get LNK2001 errors.

like image 347
maffo Avatar asked Dec 07 '22 21:12

maffo


1 Answers

 MWTypes returned = rowSet.getElement();

 // lastly I want to get the value in the returned type
 long foo = returned.get();

should be

 MWTypes* returned = &rowSet.getElement();

 // lastly I want to get the value in the returned type
 long foo = returned->get();

or

 MWTypes& returned = rowSet.getElement(); // actually illegal, but MSVC will let you do

 // lastly I want to get the value in the returned type
 long foo = returned.get();

Indeed, polymorphic calls must be made via a pointer or a reference.

EDIT: this is not your only problem. The fact that the vector stores objects (and not pointers) will slice the objects and destroy their type information.

See this faq entry for additional info to help you solve your problem and understand how virtual functions are called.

like image 56
Alexandre C. Avatar answered Dec 28 '22 05:12

Alexandre C.