Lame Fanello Lame Fanello - 2 months ago 6
C++ Question

How to use classes in C++?

I can't see to find the problem in my code. Nor the solution on the internet. I can see that i can create the code in a different way but i need to know how to work with it written like this:

class Triunghi{
int l1=0;//latura1
int l2=0;//latura2
int ba=0;//baza
int p=0;//perimetru
public:
Triunghi(){}
Triunghi(int a):l1(a){}
Triunghi(int a,int b):l1(a),l2(b){}
Triunghi(int a,int b,int c):l1(a),l2(b),ba(c){}
Triunghi(int a,int b,int c,char *msg):l1(a),l2(b),ba(c){
cout<<msg<<""<<l1<<l2<<ba<<endl;
}
Triunghi(Triunghi &A){
l1=A.l1;
l2=A.l2;
ba=A.ba;
}
~Triunghi(){
}
int Perimetru()
{
p=l1+l2+ba;
return (p);
}
};


It works fine there are no errors but i cant seem to give value to l1, l2 and ba, to use them in function 'Perimetru'.
This is how my main looks.

int main()
{
Triunghi tri;
Triunghi(1,2,3);
tri.Perimetru();
return 0;
}


How to make it work?

Answer
Triunghi tri;
Triunghi(1,2,3);

This doesn't do what you think it does. tri is created with default constructor, so all of your members are set with their in-class default values, meaning 0. Then, you create temporary object Triunghi, and you don't even use it. What you might wanted to do instead is:

Triunghi tri(1,2,3);

Then Perimetru() returns 6 as expected.

Comments