bahrami703i
bahrami703i

Reputation: 33

declare a classmember in another

I am trying to have a member in a class from another class: I have a blog class and friends class and a blog_pointer class i tried the code below:

friends :: blog_pointer *  blogFriend;

is there any thing like prototype in function for classes? compiler except a constructor or destructor.

Upvotes: 1

Views: 80

Answers (2)

jnfjnjtj
jnfjnjtj

Reputation: 489

You can forward-declare or "prototype" classes like this:

class B;

class A {
  public:
    B b;
};

class B {
  public:
    A a;
};

Upvotes: 2

nate_weldon
nate_weldon

Reputation: 2349

friend keyword only grants access to the other classes private data members. You can not declare additional members of another class inside a friend class.

Rectangle.h

class Rectangle {
  int width, height;
 public:
  int area ()
    {return (width * height);}
  void convert (CSquare a);
  };

Square.h

class Square {
 private:
   int side;
public:
  void set_side (int a)
     {side=a;}
friend class Rectangle;
};

Rectangle.cc

void Rectangle::convert (Square a) {
width = a.side;
height = a.side;
}

main.cc

int main () {
 Square sqr;
 Rectangle rect;
 sqr.set_side(4);
 rect.convert(sqr);

}

with out the friend keyword you can access a.side in the convert method.

But i'm not really sure what you are asking? If you just want to use another class you can do the following.

NextSquare.h

class NextSquare {
 private:
   int side;
public:
  void set_side (int a)
     {side=a;}
friend class Rectangle;
class Rectangle* aRecInASquare;
};

You can now access Rectangle's data in NextSquare

Upvotes: 0

Related Questions