kollarotta
kollarotta

Reputation: 9

class with a pointer member

class Block 
{
    Block *on;
    char *name;
    bool white;
    bool clear;
    bool onTable;
public:
    Block(char *nm);
    Block(const Block &ob);
    void setName(char *nm);
    char *getName() const ;
    bool isClear();
    void setColor(int colour);
    bool isWhite()const;
    bool isOnTable();
    Block *getOn();
    void putOn(Block &block);
    void putOnTable();
    void takeFromTable();
    void makeClear();
    void flipColor();
    void print();
};

I have class like this. Why the declaration of *on pointer like Block *on? Don't we have to write int, float or something like that first? What is the purpose?

Block *getOn() function out of the class declaration is like this;

Block *Block::getOn()
{
    return on;
}

I need to return on pointer in this code. Is there any other way to do that?

Upvotes: 0

Views: 72

Answers (2)

Arun
Arun

Reputation: 2092

If you don't want to manage raw pointers (as I do), prefer smart pointers instead.

Ex:

     // declare type
    typedef std::shared_ptr<Block> BlockPtr;

    class Block 
    {
        BlockPtr on; // using smart pointer instead of raw pointer
        char *name;
        bool white;
        bool clear;
        bool onTable;
    public:
        Block(char *nm);
        Block(const Block &ob);
        void setName(char *nm);
        char *getName() const ;
        bool isClear();
        void setColor(int colour);
        bool isWhite()const;
        bool isOnTable();
        BlockPtr getOn(); // returning smart pointer
        void putOn(Block &block);
        void putOnTable();
        void takeFromTable();
        void makeClear();
        void flipColor();
        void print();
    };   

    // initializing on
    on = BlockPtr(new Block);

Upvotes: 0

atomicinf
atomicinf

Reputation: 3736

Block * on declares on as a pointer to an object of type Block. When you write a class definition (in this case defining class Block), you're really inventing a whole new datatype (in this case Block), describing what kind of data it contains as well as what operations are possible.

Your getOn() code looks correct.

Upvotes: 1

Related Questions