How to make a polymorphic pointer with this pointer in the parameter?

2

For example, in Qt (correct me, if logic is wrong, I have not done Qt for a long time), you can do this:

QLabel label = new QLabel(this);

Now let's suppose:

#include <iostream>
class AbstractBase
{
    public:
        virtual void A() = 0;
};

class DerivedClass : public AbstractBase
{
public:
    void A()
    {
        std::cout << "ClassA";
    }
    DerivedClass(AbstractBase* Base)
    {
        A();
    }
};
int main()
{
    AbstractBase* A = new DerivedClass(this);
}

But the compiler returns: "invalid use of this in non-member function". What is the correct way to add the 'this' parameter in this case? (% of%, why it is derived.) Is this possible (refer to A as the parameter)?

    
asked by anonymous 11.02.2014 / 17:22

3 answers

0

The example of QLabel with the parameter this makes sense if the code is running in the context of a class that can contain a QLabel , an instance of QWidget , since the first parameter would be the parent element of the label.

However, outside of a class that implements QWidget , the code will not work.

In your case, I think you just need to create the class, without this as an argument:

 AbstractBase* A = new DerivedClass;
    
11.02.2014 / 17:36
2

The expression this results in a pointer to the object where you are currently calling the member function. It does not make sense to write this out of a member function since there is no object in this case and the compiler will complain.

If you want a pointer to the current object inside the constructor, simply type this . You do not need to read it as a parameter. The type of this will be that of the class in which you write the expression, but you can convert it to a base class with no problems.

DerivedClass()
{
    DerivedClass* self = this;
    AbstractBase* base = (AbstractBase*)this;
}

In the case of the Qt example you wrote, this line should appear inside a class. The goal is to move to QLabel who is your relative.

Another problem:

AbstractBase* obj = new DerivedClass(obj);

This is valid. But note that the constructor is going to run before that the obj variable receives the object. So the value passed as argument here is rubbish. The clang gives the following alert:

  

warning: variable 'obj' is uninitialized when used within its own initialization [-Wuninitialized]

    
11.02.2014 / 18:25
1

I do not quite understand what the purpose of the code is, but you're using the keyword this outside the context of a class's method, that's what's wrong.

this A pointer to the class of the current context, as you are inside a function and not a method, there is no class context valid for you at this point, hence the error generated by the compiler.

    
11.02.2014 / 17:32