0

I'm new to C++ classes, and I have some questions about nested classes.

What I Know

  1. classes in C++ are set of variables and functions set by 'private' by default.
  2. when you create a class, an object is created.
  3. I understand the basic concepts of constructors.

I know that I can make 'classes' as an variable in an another 'class', also known as nested class, but I really can't figure out how it is done exactly. If I create an nested class, does it create object itself, and objects from the class variables inside the nested class?

I'm having problems initializing class variables in nested class using constructors.

For example

class Point {
int xpos;
int ypos; 
}

Let's say that I created a class containing 2 int variables.

class Rectangle {
Point upLeft;
Point lowRight;
}

Then, I created a Rectangle class having 2 'Point class' as variables.

Rectangle rec1;

Then, I created an object rec1.

How can I initialize the 2 xpos and 2ypos using constructors in Rectangle Class?

  • You will [find the answer to your question here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Sam Varshavchik Sep 14 '17 at 00:21
  • Grab your text book and look up "Member Initializer List". – user4581301 Sep 14 '17 at 00:22
  • "Nested class" means something entirely different in C++, which you're not doing here. What you have is "members with class type". "When you create a class, an object is created" is confusing and not true. I think what you meant there was "When you define a variable with class type, an object is created." (Note that "object" is also a technical term which is not limited to class types! Variables with fundamental types like `int` or `double`, pointer types, or array types all name objects too.) – aschepler Sep 14 '17 at 01:41

1 Answers1

0

You need add a constructor, here is a simple example:

class Point {
public:
    Point(int x, int y) : xpos(x), ypos(y) {}
private:
    int xpos;
    int ypos; 
};


class Rectangle {
public:
    Rectangle(int x1, int y1, int x2, int y2) : upLeft(Point(x1, y1)), lowRight(Point(x2, y2)) {}
private:
    Point upLeft;
    Point lowRight;
};
上山老人
  • 412
  • 4
  • 12
  • 2
    Note that it isn't necessary to construct a temporary `Point` prior to constructing the points in the `Rectangle`, as you can do `upLeft(x1, y1)` directly rather than `upLeft(Point(x1, y1))`. (It doesn't matter for a simple case like the one here, but for larger objects, or objects without move or copy constructors it could be important). – Mankarse Sep 14 '17 at 01:32