Search code examples
c++oopclassinheritancefriend-class

friend class doesn't do well with me?


I am trying to deal with friend class for the first time. I wrote the code below:

class Kind{

private:
    friend class Type;
    int x;

public:
    Kind(){ x=0; }
    void setX(int X) { x =X; }
    int getX() { return x; }

    };

class  Type: public Kind {
    public:
    friend class Kind;
    Type(){ }
    Kind root;
    root.x=3;

};

The compiler tells me that I can not do root.x=3;, What is the problem??


Solution

  • The problem is your trying to execute a statement in a place where the compiler is expecting member declarations. Try putting it into a method

    class Type : public Kind {
      ...
      void Example() {
        Kind root;
        root.x = 3;
      }
    };