JaySilk84
JaySilk84

Reputation: 970

c++ Better way to assign a derived class to a base class

This seems like a silly question but I want to be able to instantiate a derived class and assign it to a base class in one line:

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

// i can do this
A *base;
B derived;
base = &derived;

// i'd like to do something like this
A *base;
base = &B(); // produces a warning: taking address of temporary

I'm trying to get polymorphic behavior without using the new operator. I think the compiler is inserting a temporary reference to the return value of the constructor. Is it possible to instruct the compiler that I actually want to use that address for the assignment?

* EDIT

Here's a little context. I have something like this when parsing an xml file:

class element { virtual void load_xml(...); };
class city : public element { ... };
class state : public element { ... };

element *base;
// read some xml

if (xml_node == "city") {
  base = &city(); 
} else if (xml_node == "state") {
  base = &state();
} 

base.load_xml(...);

The idea is that each derived node knows how to hydrate itself and will override the load_xml() function to do so. I guess what I should really be doing is calling load_xml in each if block rather than try and assign each derived class to the base then call load_xml from the base at the end.

Thanks!

Upvotes: 5

Views: 1053

Answers (2)

K-ballo
K-ballo

Reputation: 81349

I want to be able to instantiate a derived class and assign it to a base class in one line

An object instantiated within a single line (without using the new operator) will last only until the end of the expression that evaluates it. So by the point you have the address, the temporary does no longer exist.

I'm trying to get polymorphic behavior without using the new operator.

To do that, you need a named variable to have a valid lifetime for your object.

Upvotes: 4

Ayjay
Ayjay

Reputation: 3433

This isn't about derived classes - you are trying to take the address of a temporary variable. You need to work out where you want the object to be stored, on the stack or the heap.

Stack:

B derived; // this works as an A any place you need it to

Heap:

A* derived = new B();

Upvotes: 3

Related Questions