duerdak
duerdak

Reputation: 57

Creating a class object without a variable

So I create my class Cars. Then I make a variable(audi) for an object from my class cars. Everything is fine and dandy but I noticed that I can create an object(with an engine value of 50) without specifying a variable for it to be held in. So now how can I access that object?

#include <iostream>

using namespace std;

class Cars
{
public:
    int getStatus();
    Cars(int engine=5);
private:
    int m_engine;
};
Cars::Cars(int engine)
{
    m_engine=engine;
    cout<<"A new car is made."<<endl;
}
Cars::getStatus()
{
    cout<<m_engine<<endl;
}

int main()
{
    Cars audi(10);
    audi.getStatus();
    Cars(50);

}

Upvotes: 1

Views: 1101

Answers (3)

Aconcagua
Aconcagua

Reputation: 25536

It depends on when you want to access the object.

Cars(50);

With this piece of code, you create a temporary object that lives only during execution of the current statement (i. e. until execution of your code passes the semicolon).

Cars(50);
// I want to access the object here

In this case: Too late. The temporary has already been destroyed and doesn't exist any more. No chance to get back to it. You can, however, use the object as long as it lives, e. g. call a member function on it or pass it to another function:

Cars(10).doSomething();
// but right now (after the semicolon), the car doesn't exist any more
doSomethingElse(Cars(12));
// again, the object got destroyed

Be aware that in above example, you created two distinct instances, each ceasing to exist when reaching the semicolon. Be aware, too, that the objects' destructors get called at this point of time.

Upvotes: 5

gsamaras
gsamaras

Reputation: 73384

You need to do it all together, like this:

Cars(50).getStatus(); 

Otherwise you won't have a way to refer to your car with 50 m_engine.

This temporary should be used with fidelity. Read more in What is an Anonymous Object?

Upvotes: 2

Quentin
Quentin

Reputation: 63144

You can't! It's already dead by the time you try. Cars(50) is a temporary, and its lifetime ends at the end of its full-expression -- that is, at the ;.

Upvotes: 0

Related Questions