Jack
Jack

Reputation: 258

Calling a class's constructor inside another class

I have a test next week for c++ and I'm preparing myself for it. I'm confused when I have 2 classes as shown below. I have to walk through the execution of the code, line by line, and I'm confused about the marked lines (x = ... and y = ... inside class two) - where does execution go from there?

#include <iostream>
using namespace std;

class one {
    int n;
    int m;
    public:
    one() { n = 5; m = 6; cout << "one one made\n"; }
    one(int a, int b) {
        n = a;
        m = b;
        cout << "made one one\n";
    }
    friend ostream &operator<<(ostream &, one);
};

ostream &operator<<(ostream &os, one a) {
    return os << a.n << '/' << a.m << '=' <<
        (a.n/a.m) << '\n';
}

class two {
    one x;
    one y;
    public:
    two() { cout << "one two made\n"; }
    two(int a, int b, int c, int d) {
        x = one(a, b);  //here is my problem
        y = one(c, d);  //here is my problem
        cout << "made one two\n";
    }
    friend ostream &operator<<(ostream &, two);
};

ostream &operator<<(ostream &os, two a) {
    return os << a.x << a.y;
}

int main() {
    two t1, t2(4, 2, 8, 3);
    cout << t1 << t2;
    one t3(5, 10), t4;
    cout << t3 << t4;
    return 0;
}

Upvotes: 1

Views: 9969

Answers (3)

Marius
Marius

Reputation: 837

Current approach works only if you have a default constructor in one class. It is better to initialize members in constructor initialization list:

two(int a, int b, int c, int d) 
    : x(a,b), y(c,d)
{
        cout << "made one two\n";
}

Upvotes: 2

FlyingFoX
FlyingFoX

Reputation: 3509

x = one(a, b);  //here is my problem
y = one(c, d);  //here is my problem

What this code does is that it calls the constructor of the class one and assigns the newly created instance of this class to the variables x and y.

The constructor of class one is in line 9.

Upvotes: 2

weima
weima

Reputation: 4912

from the line x = one(a, b); it jumps to line one(int a, int b) and executes the parameterized constructor of one

same for line y = one(c, d);

Upvotes: 3

Related Questions