for some reason i have to declare multiple classes in the same file, and in paricoular I have to use an object of one of these classes before declaring, here is an example:
#include<iostream>
using namespace std;
class square{
double side;
double area;
square(double s){
side = s;
}
void calcArea(){
area = side*side;
}
void example(){
triangle t(2.3,4.5);
t.calcArea();
}
};
class triangle{
double base;
double height;
double area;
triangle(double s,double h){
base = s;
height = h;
}
void calcArea(){
area = (base*height)/2;
}
};
int main(){
}
You can see that in example() method in square class, I use an object belonging to class triangle that is declared after its use. There's a way in order to let work this pieces of code?
Since square needs triangle, but triangle doesn't need square, you can simply change the order of the class definitions:
class triangle {
// ...
};
class square {
// ...
};
Or, since example is the only thing in square that needs triangle, define example after the definition of triangle:
class square {
// ...
void example();
};
class triangle {
// ...
};
void square::example() {
triangle t(2.3,4.5);
t.calcArea();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With