Also you are allocating dynamically but I don't see your destructor so that memory is not freed.
You should have a destructor that deletes these guys
player1 = new Player;
player2 = new Player;
ball = new Ball;
Logic::~Logic()
{
delete player1;
delete player2;
delete ball;
}
Though player and ball being a member of logic doesn't make much sense :)
You should also watch out for memory leaks that might occur in your constructor.The thing is in C++ when a class throws an exception from the constructor its destructor is never called.So imagine what happens when
player1 = new Player;
player2 = new Player;
allocate memory and then new Ball;(constructor of Ball) throws an exception.This means ~Logic will not be called and you won't be able to delete player1 and player2.
Here is an example that shows this :
#include <iostream>#include <string>#include <exception>#include <memory>using std::cout;using std::endl;class Player{public : Player() { cout<<"Player constructor called"<<endl; } ~Player() { cout<<"Player destructor called"<<endl; } };class Ball{public : Ball() { throw std::runtime_error("Ball threw exception"); cout<<"Ball constructor called"<<endl; } ~Ball() { cout<<"Ball destructor called"<<endl; }};class Logic{public: Logic(): player1(new Player()), player2(new Player()), ball(new Ball()) { } ~Logic() { } Player* player1; Player* player2; Ball* ball;};int main(){ try { Logic gameLogic; } catch(const std::runtime_error& e) { cout<<e.what()<<endl; } return 0;}
And here is how it is fixed by using a shared_ptr
#include <iostream>#include <string>#include <exception>#include <memory>using std::cout;using std::endl;class Player;class Ball;typedef std::tr1::shared_ptr<Player> PlayerPtr;typedef std::tr1::shared_ptr<Ball> BallPtr;class Player{public : Player() { cout<<"Player constructor called"<<endl; } ~Player() { cout<<"Player destructor called"<<endl; } };class Ball{public : Ball() { throw std::runtime_error("Ball threw exception"); cout<<"Ball constructor called"<<endl; } ~Ball() { cout<<"Ball destructor called"<<endl; }};class Logic{public: Logic(): player1(new Player()), player2(new Player()), ball(new Ball()) { } ~Logic() { } PlayerPtr player1; PlayerPtr player2; BallPtr ball;};int main(){ try { Logic gameLogic; } catch(const std::runtime_error& e) { cout<<e.what()<<endl; } return 0;}
To understand how this works you need to read on stack unwinding and what happens when an exception is thrown.