validity of using subclasses in pointer-to-pointer types?

M

Marcus Alanen

Hello everybody, I'm having a bit of trouble with the following code.
I have a class A, and its subclass B. Then, a variable "a" of type A**,
and one "b" of type B*.

class A {
};
class B : public A {
};

A** a;
B* b;

int main() {
a = &b;
}


For some reason I can't assign "a = &b". I've tested it with g++ version
3.3 and Intel's C compiler (icc version 7.0) and both give similar
errors:

G++:
test.cpp: In function `int main()':
test.cpp:14: invalid conversion from `B**' to `A**'

ICC:
test.cpp(14): warning #556: a value of type "B **" cannot be assigned to
an entity of type "A **"
a = &b;

So it certainly sounds like this is not valid C++, but I can't help to
wonder why not? "a" is supposed to be a double indirection to an object
of type A, and since B is a subclass of type A, I would've thought this
would work. In fact, saying "a = &static_cast<A*>(b)" compiles with g++,
whereas icc says:

test.cpp(14): error: expression must be an lvalue or a function designator
a = &static_cast<A*>(b);


On a final note, using "A* a" and "B b" works nicely on both compilers,
so why shouldn't "A** a" and "B* b"?

Any comments would be much appreciated. It's not a problem I can't do
some workaround for, but I'd like to extend my knowledge of C++ here.
Thanks in advance for any feedback!

Regards,

Marcus
 
A

Alf P. Steinbach

Hello everybody, I'm having a bit of trouble with the following code.
I have a class A, and its subclass B. Then, a variable "a" of type A**,
and one "b" of type B*.

class A {
};
class B : public A {
};

A** a;
B* b;

int main() {
a = &b;
}


For some reason I can't assign "a = &b". I've tested it with g++ version
3.3 and Intel's C compiler (icc version 7.0) and both give similar
errors:

G++:
test.cpp: In function `int main()':
test.cpp:14: invalid conversion from `B**' to `A**'

ICC:
test.cpp(14): warning #556: a value of type "B **" cannot be assigned to
an entity of type "A **"
a = &b;

So it certainly sounds like this is not valid C++, but I can't help to
wonder why not?


Consider the effect of allowing the following code:


#include <iostream>

struct A {};
struct B: A { int x; B(): x(1234) {}; virtual int f(){ return x; } };

int main()
{
A a;
B b;
B* p = &b;
B** pp = &p;
A** pFudge = &p; // Not allowed, but suppose it is?

*pFudge = &a; // Changes value of 'p'.
std::cout << p->f() << std::endl; // <-- Bang, crash.
}


Essentially the same problem as with T const**, which you'll find in
the FAQ.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top