| re: converting pointer to const ref
"cppaddict" <cppaddict@yahoo.com> wrote in message
news:MoKib.892$vc4.637@newssvr27.news.prodigy.com[color=blue]
> I can't figure out why this code won't work, or how to fix it:
>
> list<MyClass> l;
> int main() {
> for (int i=0;i<5;i++) {
> MyClass* myClass = new MyClass;
> myClass -> someInitMethod();
> l.push_back(myClass);
> }
> }
>
> The compiler errors on "l.push_back(myClass)", saying that it can't
> convert MyClass* to const MyClass&.
> Two questions:
>
> 1. Why can't it do this conversion?[/color]
Why should it? C++ is a typed language, which means that variables of
different types are not interchangeable (some limited conversions/casts are
possible, but conversions are not universally available). myClass is a
pointer to a MyClass object, but the list does not store pointers, it stores
MyClass objects.
[color=blue]
> 2. How do you make this code work?[/color]
Either change the list so it stores pointers (i.e., use list<MyClass*> l) or
add objects rather than add pointers to the list (i.e., use
l.push_back(*myClass) ). Whether either option represents the best design is
another issue.
--
John Carson
1. To reply to email address, remove donald
2. Don't reply to email address (post here instead) |