C++ Classes and Objects-Jan
C++ Classes and Objects-Jan
WRITTEN BY:
ACSC 328: Object Oriented Copyright © UNIVERSITY OF EMBU,JANUARY2022
Dr. E.C TOO
Programming(C++)
1
All Rights Reserved
Classes and Objects
Class Definitions and Objects
Member Functions
Data Members
Get and Set functions
Constructors
int main() {
MyClass myObj; // Create an object of MyClass
Example
width = x;
#include <iostream>
height = y;
using namespace std;
}
class Rectangle {
int main () {
int width, height; Rectangle rect;
public: rect.set_values (3,4);
}
};
EXERCISES
Write a program to print the area and perimeter of a triangle having
sides of 3, 4 and 5 units by creating a class named 'Triangle' with a
function to print the area and perimeter.
Write a C++ program that will implement a class named sphere. The
program should accept the radius and determine the volume. The
program should then output the volume. Use pie as 3.14.
volume=4/3πr3.
SOLUTION…
#include <iostream>
#include <string>
int main()
#include <cmath>
using namespace std;
{
class Triangle
{
Triangle t;
public:
void print_area(int s1, int s2, int s3)
{
double s = (s1+s2+s3)/2.0;
t.print_area(3,4,5);
cout << s << endl;
cout << "Perimeter is " << (s1+s2+s3) << endl;
return 0;
};
}
}