0
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?

kollarotta
  • 9
  • 2
  • 4
  • If you didn't make it a pointer, it would be infinite recursion to figure out the size of your class. – chris Apr 09 '13 at 00:31
  • 3
    `on` is a pointer to an instance of type `Block`. I strongly suggest reading a [good introductory book on C++](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)... – Oliver Charlesworth Apr 09 '13 at 00:32

2 Answers2

1

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.

atomicinf
  • 3,596
  • 19
  • 17
0

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);
Arun
  • 2,087
  • 2
  • 20
  • 33