2
For example, in Qt (correct me, if the logic is wrong, I haven’t touched Qt in a while), 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? (AbstactClass*
, why it is derived. ) This is possible (reference A as the parameter)?
The error stated is why you are using
this
outside the context of a class. You will need a variable of the typeAbstractBase*
there. Other than that, you’re calling a virtual method in a constructor, which doesn’t work in C++.– C. E. Gesser
Is this just a test of yours or part of a larger program? What do you really want to do?
– C. E. Gesser
@C.E.Gesser The example is representative;
– user2692
Okay, but I think we need more inputs. You don’t use the parameter
Base
, for example, so it is complicated to suggest something without knowing what it will be used for.– C. E. Gesser
@C.E.Gesser See the editions.
– user2692
I made a mistake asking; I will delete the question.
– user2692
Um... I still don’t see your need to pass the parameter in this case. You want to do something like Qt, where you pass an object that will be the owner of the newly constituted object?
– C. E. Gesser
@C.E.Gesser Qt is just one example.
– user2692
It’s that you can’t use
this
where are you using, becausethis
means "a pointer to the object under which the current method is being invoked", and you are in the functionmain
, which is a free function, is not a member of any object.– C. E. Gesser