[Insight-developers] Obscure g++ error message
Brad King
brad.king@kitware.com
Wed, 2 May 2001 17:04:07 -0400 (EDT)
> I am trying to write a test program for a new ResampleImageFilter
> class and am getting a g++ error message that my C++ knowledge is
> insufficient to interpret. It looks like someone, somewhere is
> declaring `this' to be const, but I can't locate the somewhere or
> someone; it's also possible that I've completely misunderstood the
> problem. Could anyone interpret this error for me?
When you call a method on an object, the compiler automatically makes the
object the "this" argument to the method. If your object has a const
qualifier on it, then the "this" argument will also be const. You cannot
call a non-const method on a const object.
Here is an example:
struct Foo
{
// In both methods below, there is a hidden "this" argument which points
// at the object on which the method was invoked.
void NormalMethod()
{
// The type of the variable "this" is "Foo*", which is read as
// "Pointer to Foo"
}
void ConstMethod() const
{
// The type of the variable "this" is "const Foo*", which is read as
// "Pointer to const Foo"
// Because the target of the "this" pointer has a const qualifier,
// we are not allowed to modify the object here.
}
};
void f(Foo* foo)
{
// "foo" is of type "Pointer to Foo"
foo->ConstMethod(); // Okay.
foo->NormalMethod(); // Okay.
}
void g(const Foo* foo)
{
// "foo" is of type "Pointer to const Foo"
foo->ConstMethod(); // Okay, method is declared "const".
foo->NormalMethod(); // Error, method is not declared "const".
}
In the call to NormalMethod() in g(), the error produced will read
something like:
ERROR: cannot pass object "foo" of type "const Foo*" as "this"
argument of "Foo::NormalMethod()" without discarding qualifiers.
What this means is you are trying to convert "foo" from type
"const Foo*" to type "Foo*", which removes the "const", and is not
allowed.
All of the above boils down to this: somewhere you are trying to call a
non-const method on a const object. Most likely the error is in
/home/hughett/work/Insight/Code/BasicFilters/itkResampleImageFilter.txx,
at line 113, but since the code uses templates, the real problem may be
somewhere else (where the class was instantiated, for example).
-Brad