Declaring an object before initializing it in c++

前端 未结 10 2197
你的背包
你的背包 2020-12-13 17:17

Is it possible to declare a variable in c++ without instantiating it? I want to do something like this:

Animal a;
if( happyDay() ) 
    a( \"puppies\" ); //c         


        
10条回答
  •  無奈伤痛
    2020-12-13 17:40

    Yes, you can do do the following:

    Animal a;
    if( happyDay() )
        a = Animal( "puppies" );
    else
        a = Animal( "toads" );
    

    That will call the constructors properly.

    EDIT: Forgot one thing... When declaring a, you'll have to call a constructor still, whether it be a constructor that does nothing, or still initializes the values to whatever. This method therefore creates two objects, one at initialization and the one inside the if statement.

    A better way would be to create an init() function of the class, such as:

    Animal a;
    if( happyDay() )
        a.init( "puppies" );
    else
        a.init( "toads" );
    

    This way would be more efficient.

提交回复
热议问题