In C#, in order to instantiate a class we use the ‘new’ keyword.
In C++ why don’t we make the same?
It fells strange to simply put a
FBullCowGame BCGame;
is just like saying
int someinteger;
and expect to respond to a value.
In C#, in order to instantiate a class we use the ‘new’ keyword.
In C++ why don’t we make the same?
It fells strange to simply put a
FBullCowGame BCGame;
is just like saying
int someinteger;
and expect to respond to a value.
Because new
would make a heap allocation and return you a pointer to that memory address where it was allocated. Doing FBullCowGame BCGame;
implicitly calls the default constructor which should initialise the data members of the class on the stack.
I have a related question: Does not using “new” still create a FBullCowGame object (In C#, doing so would result in a “null” variable)? And if so, doesn’t mean that it allocate memory anyway for that object? I’m not really sure that I understand what you mean by “a heap allocation”.
Also, could our constructor take parameters and, if so, wouldn’t force us to use “new”?
Yes.
class FBullCowGame
{
int MyMaxTries = 5;
int MyCurrentTry = 1;
};
int main()
{
FBullCowGame BCGame; //BCGame.MyCurrentTry = 1, BCGame.MyMaxTries = 5
}
Note that this is different for the built-in types as they don’t have constructors so int MyInt;
is an uninitalised variable
Yes but it allocates it on the stack. Further reading: https://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap
Yes it can and no, new
still doesn’t need to be used.
class FBullCowGame
{
public:
FBullCowGame(int CurrentTry, int MaxTries) : MyCurrentTry(CurrentTry), MyMaxTries(MaxTries) {}
private:
int MyMaxTries = 5;
int MyCurrentTry = 1;
};
int main()
{
FBullCowGame BCGame(10, 20); //BCGame.MyCurrentTry = 10, BCGame.MyMaxTries = 20
}