What is the compiler doing with object creation?

Nikolas Fraser 60 Reputation points
2024-03-02T22:38:21.22+00:00

I'm writing in C++ using Visual Studio and ran in to a problem I don't understand at all: I added a constant integer to one of my objects which caused the compiler to ?delete the constructor?

Removing 'const' from the integer allows the constructor to survive. Using 'const' and creating a pointer to the object on the heap also allows the constructor to survive.

It says that the function was declared implicitly, yet I've very explicitly written the constructor for the object.

// error as shown below

game = Game();

C++ function "Game::operator=(const Game &)" (declared implicitly) cannot be referenced -- it is a deleted function

// perfectly fine

Game* game = new Game();

So, it seems there's a lot more going on under the hood than creating an object on the stack vs. the heap. I would like to know what is actually happening and why the compiler is declaring its own functions then deleting them in the first case.

Thanks for any information.

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,689 questions
{count} votes

Accepted answer
  1. RLWA32 44,951 Reputation points
    2024-03-03T08:48:49.2266667+00:00
    game = Game();
    

    The above line of code is calling the Game class copy assignment operator ( the deleted function). The compiler complains because a const member variable of type int can be initialized but does not allow for assignment of values (otherwise it wouldn't be const).

    Game* game = new Game();
    

    This line of code creates a Game object on the heap and assigns its address to the *game pointer variable. There is no attempt to copy anything into a const member variable.

    Game game = Game();
    

    The line of code creates a Game object on the stack and uses a copy constructor. If your code doesn't contain a copy constructor for the Game class the compiler provides one for you. If you tried to write a copy constructor like this

        Game(const Game& rhs)
        {
            i = rhs.i;
        }
    
    private:
        const int i;
    

    then the compiler would complain about the assignment to a const variable (error C2789: 'Game::i': an object of const-qualified type must be initialized). However, if you wrote a copy constructor like this

        Game(const Game& rhs) : i(rhs.i)
        {
        }
    
    private:
        const int i;
    

    then the compiler is OK since the const member variable is being initialized.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.