member functions in class

#include<iostream.h>
#include<conio.h>
#include<math.h>
class triangle
{
private:
float b,h,area,perimeter;

public:
void cal_area(float b,float h)
{
area=(1/2)*b*h;
cout<<area;
}
void cal_perimeter(float b,float h);
void input()
{
cout<<"enter base and height";
cin>>b>>h;
cal_area(float b,float h);
cal_perimeter(float b,float h);
}

};
void triangle::perimeter(float b,float h)
{
perimeter=b+h+pow(b*b+h*h,0.5);
cout<<perimeter;
}
int main()
{
triangle tr1;
tr1.input();
getch();
}

but there r many errors..plz help me find out
You can't just start writing the elements of the function in the class.
Do it outside the class.

eg:

1
2
3
4
5
6
7
8
9
10
class triangle {
      public:
      void cal_area(float b, float h);
};

void triangle::cal_area(float b, float h)
{
      area=(1/2)*b*h;
      cout<<area;
}
I did not test the code but hope that it can contain only simple typo that can be easily updated.

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <cmath>
#include <conio.h>

class triangle
{
private:
   float b, h, area, perimeter;

public:
   float cal_area()
   {
      area = 0.5 * b * h;
      return ( area );
   }
   float cal_perimeter();
   void input()
   {
      std::cout << "enter base and height: ";
      std::cin >> b >> h;
   }
};

float triangle::perimeter()
{
   perimeter = b + h + std|::pow( b * b + h * h, 0.5 );
   return ( perimeter );
}

int main()
{
   triangle tr1;

   tr1.input();
   std::cout << "area = " << tr1.cal_area() << std::endl;
   std::cout << "perimeter = " << tr1.cal_perimeter() << std::endl;

   getch();
   return ( 0 );
}
Last edited on

@Aceix
You can't just start writing the elements of the function in the class.


Why does he can not start writing elements of the function in the class when he can?:)


@vgoel38


This expression

area=(1/2)*b*h;

will be always equal to zero because for integer numbers 1/2 is equal to zero.

Here

cal_area(float b,float h);
cal_perimeter(float b,float h);

you shall specify arguments not parameters. So the calls look like

cal_area(b,h);
cal_perimeter(b,h);

But in any case my design of the class that I showed above is better. b and h are members of the class so there is no need to pass it to member functions as arguments.

Last edited on
I didn't know dat
Topic archived. No new replies allowed.