Calling a constructor to re-initialize object

前端 未结 12 1711
执笔经年
执笔经年 2020-12-04 15:01

is it possible to re-initialize an object of a class using its constructor?

相关标签:
12条回答
  • 2020-12-04 15:36

    Sort of. Given a class A:

    A a;
    ...
    a = A();   
    

    the last statement is not initialisation, it is assignment, but it probably does what you want.

    0 讨论(0)
  • 2020-12-04 15:39

    I usually write the following in modern C++ :

    SomeClass a;
    ...
    a = decltype(a)();
    

    It may be not the most effective way, as it effectively constructs another object of the same type of a and assigns it to a, but it works in most cases, you don't have to remember the type of a, and it adapts if the type changes.

    0 讨论(0)
  • 2020-12-04 15:40

    While most answers are reinitializing an object in two steps; first, creating an initial object, and second creating another object and swapping it with the first one using placement new, this answer covers the case that you first create a pointer to an empty object and later allocate and construct it:

    class c *c_instance; // Pointer to class c
    c_instance = new c(arg1, ..., argn) // Allocate memory & call the proper constructor 
    // Use the instance e.g. c->data
    delete c_instance; // Deallocate memory & call the destructor 
    
    0 讨论(0)
  • 2020-12-04 15:42

    Instead of destructing and reinitializing as suggested by some of the answers above, it's better to do an assignment like below. The code below is exception safe.

        T& reinitialize(int x, int y)
        {
            T other(x, y);
            Swap(other); // this can't throw.
            return *this;
        }
    
    0 讨论(0)
  • 2020-12-04 15:44

    May-be not what you have in mind, but since you didn't mention what it is for, I suppose one answer would be that you'd do it by controlling scope and program flow.

    For example, you wouldn't write a game like this:

    initialize player
    code for level 1
    ...
    reinitialize player
    code for level 2
    ...
    etc
    

    Instead you'd strive for:

    void play_level(level_number, level_data) {
        Player player; //gets "re-initialized" at the beginning of each level using constructor
        //code for level
    }
    
    void game() {
        level_number = 1;
        while (some_condition) {
            play_level(level_number, level_data);
            ++level_number;
        }
     }
    

    (Very rough outline to convey the idea, not meant to be remotely compilable.)

    0 讨论(0)
  • 2020-12-04 15:44

    Yes , it is possible. If you create a method that returns a new object.

    #include "iostream"
    class a // initialize class
    a getNewA(a object){// Create function to return new a object
    a new_object(/*Enter parameters for constructor method*/);
    return new_object;
    }
    
    0 讨论(0)
提交回复
热议问题