Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ using object of a class declared after

Tags:

c++

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?

like image 848
SimCor Avatar asked Jan 28 '26 20:01

SimCor


1 Answers

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();
}
like image 123
emlai Avatar answered Jan 30 '26 10:01

emlai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!