1 Replies - 247 Views - Last Post: 14 June 2012 - 01:29 PM Rate Topic: -----

#1 Gonzo0193  Icon User is offline

  • New D.I.C Head
  • member icon

Reputation: 2
  • View blog
  • Posts: 49
  • Joined: 16-December 09

Problem with classes

Posted 14 June 2012 - 12:54 PM

EDIT: Realised i used a title with problem in it, sorry =/.

Hello. I decided to start learning C++ instead of continuing with C# so i can drop the requirement of the .net framework.

Anyway, i am having some trouble with instantiating classes. Say in C# i would do:

Player player = new Player(arg1,arg2);



I just don't get how to do this in c++. At the moment this is my players header:


Player.h
#ifndef _PLAYER_H_
    #define _PLAYER_H

#include <SDL/SDL.h>

class Player
{
    private:
        SDL_Surface* texture;
        SDL_Rect* bounds;

    public:
        Player(SDL_Surface* tex, SDL_Rect* rect);

    public:
        void Init();

        void Update();

        void Draw(SDL_Surface* screen);
};

#endif



and CApp's header

#ifndef _CAPP_H_
    #define _CAPP_H

#include <SDL/SDL.h>

#include "Player.h"

class CApp {
    private:
        bool Running;

        SDL_Surface* Surface_Display;

        SDL_Surface* Surface_Test;

        Player player;

    public:

        CApp(); //Constructor

        int OnExecute();

    public:

        bool Init();

        void Unload();

        void OnEvent(SDL_Event* Event);

        void Update();

        void Draw();
};

#endif




I just don't know how i can instantiate a player in my CApp.cpp.
Any help would be greatly appreciated :). Thanks.

This post has been edited by Gonzo0193: 14 June 2012 - 12:55 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Problem with classes

#2 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2100
  • View blog
  • Posts: 3,197
  • Joined: 21-June 11

Re: Problem with classes

Posted 14 June 2012 - 01:29 PM

Generally you initialize member variables in the initializer list of the constructor. So that would look like this:

MyClass::MyClass(Bla arg1, Blubb arg2, Blabb arg3)
    : my_member_variable(arg1, arg2)
    , my_other_member_variable(arg3)
{
    // Do other stuff
}



However from looking at your classes it seems like you might not know the arguments you want to pass to Player's constructor until some point inside CApp's constructor. If that's the case, you'll either have to change Player to have a default constructor or you'll need to change CApp's player member to be a pointer (then you can do player = new Player(arg1, arg2) in the constructor - note that you'll have to delete player in your destructor if you go that way).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1