Initializing/passing multiple values on classes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// member initialization
#include <iostream>
using namespace std;

class Circle {
    double radius;
  public:
    Circle(double r) : radius(r) { }
    double area() {return radius*radius*3.14159265;}
};

class Cylinder {
    Circle base;
    double height;
  public:
    Cylinder(double r, double h) : base (r), height(h) {}
    double volume() {return base.area() * height;}
};

int main () {
  Cylinder foo (10,20);

  cout << "foo's volume: " << foo.volume() << '\n';
  return 0;
}

the code above is an example on the tutorial, so I tried to imitate it but this time I wanted to pass(i don't know the right term if it's initialize,pass or refer) two values instead of just one...
below is my code...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
using namespace std;


class Rectangle{
int length, width;
public:
Rectangle(int l, int w): length(l), width(w) {}
int area(){ return length*width;  }
};
class Triangle{
Rectangle dim1; 
Rectangle dim2;
public:
Triangle(int l, int w): dim1(l), dim2(w){}  //I'm not so sure if this one would work...
int area(){return ??????.area()/2;}  //I really don't know how to do this... kinda lost here...
};

 int maiin(){
 Triangle asdf(10,20);
cout << "Triangle's area: " << asdf.area()/2 << '\n';
  return 0;
}

so on this code I wanted to pass the values of 10 and 20 from Triangle asdf(10,20); to the class rectangle to get the rectangle's area then half it from the class Triangle's function which is int area() to determine the triangle's area..
But I can't do it and I'm really lost and don't know what or how to do it...



Of course it is simplier to make a code like this below, to get the area of the triangle.
But I'm just really curious on how to pass multiple values from class to class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
using namespace std;
class Rectangle{
int length, width;
public:
Rectangle(int l, int w): length(l), width(w) {}
int area(){ return length*width;  }
};


int main () {
  Rectangle asdf (10,20);
  cout << "Triangle's area: " << asdf.area()/2 << '\n';
  return 0;
}




Hope someone helps me with this...
Thanks in advance
1
2
3
4
5
6
7
8
class Triangle{
    Rectangle dim1;
    //Rectangle dim2; // Not needed
public:
    Triangle(int l, int w): dim1(l, w)/*, dim2(w)*/{} // Rectangle's constructor takes 2 arguments
                                                      // So use them both!
    int area(){return dim1.area()/2;}
};
Topic archived. No new replies allowed.