T
trying_to_learn
Why do we need to explicitly call the copy constructor and the operator
= , for base class and member objects in composition?
....book says "You must explicitly call the GameBoard copy-constructor or
the default constructor is automatically called instead"
Why cant the compiler do this on its own. if we are making an object
through copr construction for an inherited class , then why not simply
call the corresponding copy constructors for base class objects or
composed objects ?
class GameBoard {
public:
GameBoard() { cout << "GameBoard()\n"; }
GameBoard(const GameBoard&) {
cout << "GameBoard(const GameBoard&)\n";
}
GameBoard& operator=(const GameBoard&) {
cout << "GameBoard:perator=()\n";
return *this;
}
~GameBoard() { cout << "~GameBoard()\n"; }
};
class Game {
GameBoard gb; // Composition
public:
// Default GameBoard constructor called:
Game() { cout << "Game()\n"; }
// You must explicitly call the GameBoard
// copy-constructor or the default constructor
// is automatically called instead:
Game(const Game& g) : gb(g.gb) {
cout << "Game(const Game&)\n";
}
= , for base class and member objects in composition?
....book says "You must explicitly call the GameBoard copy-constructor or
the default constructor is automatically called instead"
Why cant the compiler do this on its own. if we are making an object
through copr construction for an inherited class , then why not simply
call the corresponding copy constructors for base class objects or
composed objects ?
class GameBoard {
public:
GameBoard() { cout << "GameBoard()\n"; }
GameBoard(const GameBoard&) {
cout << "GameBoard(const GameBoard&)\n";
}
GameBoard& operator=(const GameBoard&) {
cout << "GameBoard:perator=()\n";
return *this;
}
~GameBoard() { cout << "~GameBoard()\n"; }
};
class Game {
GameBoard gb; // Composition
public:
// Default GameBoard constructor called:
Game() { cout << "Game()\n"; }
// You must explicitly call the GameBoard
// copy-constructor or the default constructor
// is automatically called instead:
Game(const Game& g) : gb(g.gb) {
cout << "Game(const Game&)\n";
}