Question

I know that this is probably a pointless question because it is obvious that class BASE does not have a function called pass_A, it is actually declared in another class called A and I though that using inheritance and polymorphism would allow the BASE class to see itself and the object of type A. I definitely want an object of type A to be able to call the class A from within BASE as well as BASE being declared the way it is now in init_BASE. My ultimate question is is this possible? Maybe I'm not using virtuals or something else is wrong.

What I want is for the object POLY_TYPE to be able to contain both BASE and A class types. Anyways heres the error message and the code below it.

EDITED Look at solution instead.

Était-ce utile?

La solution 2

If that's all you need to do, then just don't discard type information until you absolutely must:

A<T>* a = new A<T>;
a->pass_A(new NODE);
POLY_TYPE = a;

Edit:

You didn't post any error message on your update - funny how so many people who ask questions here believe that the actual error is irrelevant - but you also have a type problem.
Since you pass a NODE* to pass_A, the template parameter must be NODE*, not NODE.

The following compiles (cleanup of the version with no virtuals, with my tweak):

class NODE
{
public:
    NODE(){}
    ~NODE(){}
    NODE&  operator=(const NODE&) { return *this; }
};

template <class T>
class A;

template <class T>
class BASE
{    
public:
    BASE(){}
    BASE(int mode)
    {
        if(mode == 1)
        {
            init_BASE();
        }
        else if(mode == 0)
        {
            init_A();
        }
    }
private:
    void init_BASE()
    {
        POLY_TYPE = new BASE<T>;
    }

    void init_A()
    {
        A<T>* a = new A<T>;
        a->pass_A(new NODE);
        POLY_TYPE = a;
    }

    BASE* POLY_TYPE;
};

template <class T>
class A : public BASE<T>
{
public:
    void pass_A(T DATA)
    {
        this->DATA = DATA;
    }
private:
    T DATA;
};

int main()
{
    BASE<NODE*> base(1);
    return 0;
}

Autres conseils

Compiler is telling you the truth - BASE indeed does not have a member called pass_A.

Here POLY_TYPE->pass_A(new NODE()); you're trying to call pass_A through a pointer to BASE. Compiler will look up the method based on the static type of the object (that is, BASE as opposed to dynamic type, which is A - why all the caps, btw?).

You'll need to add a virtual pass_A method to the base class if you want this work.

(I'm intentionaly leaving out the fact that BASE is a template - the type is really BASE<T> where T is whatever type you instantiate the template with. It is not directly related to the problem)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top