CPP Practical
CPP Practical
Polymorphism
// Name: Syed Saad
// Roll No: 16
#include<iostream>
using namespace std;
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i =0) {real = r; imag = i;}
// This is automatically called when '+' is used with
// between two Complex objects
Complex operator + (Complex const &obj)
{
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl;
}
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
// An example call to "operator+" c3.print();
}
Output:
12+i9
Access modifiers
#include<iostream>
using namespace std;
class Circle
{
public:
double radius;
double compute_area()
{
return 3.14*radius*radius;
}
};
int main()
{
Circle obj;
obj.radius = 5.5;
cout << "Radius is: " << obj.radius << "\n";
cout << "Area is: " << obj.compute_area();
return 0;
}
Output:
Radius is: 5.5
Area is: 94.985
Static modifiers
#include <bits/stdc++.h>
using namespace std;
class Base {
public : static int val;
static int func(int a) {
cout << "Static member function called";
cout << "The value of a : " << a;
}
};
int Base::val=28;
int main() {
Base b;
Base::func(8);
cout << "The static variable value : " << b.val;
return 0;
}
Output:
Static member function called
The value of a : 8The static variable value:28
Abstract modifiers
#include <iostream>
using namespace std;
class Shape {
public:
virtual int getArea() = 0;
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
class Triangle: public Shape
{
public:
int getArea() {
return (width * height)/2;
}
};
int main(void)
{
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
cout << "Total Rectangle area: " << Rect.getArea() <<
endl;
Tri.setWidth(5);
Tri.setHeight(7);
cout << "Total Triangle area: " << Tri.getArea() <<
endl;
return 0;
}
Output:
Total Rectangle area: 35
Total Triangle area: 17
Iterators
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> v1 = { 10, 20, 30, 40 };
vector<int>::iterator itr;
cout << "Traversing without iterator : ";
for (int j = 0; j < 4; ++j) {
cout << v1[j] << " ";
}
cout << "\n";
cout << "Traversing using iterator ";
for (itr = v1.begin(); itr != v1.end(); ++itr) {
cout << *itr << " ";
}
cout << "\n\n";
v1.push_back(50);
cout << "Traversing without iterator : ";
for (int j = 0; j < 5; ++j) {
cout << v1[j] << " ";
}
cout << "\n";
cout << "Traversing using iterator ";
for (itr = v1.begin(); itr != v1.end(); ++itr) {
cout << *itr << " ";
}
cout << "\n\n";
return 0;
}
Output:
Traversing without iterator : 10 20 30 40
Traversing using iterator 10 20 30 40
Traversing without iterator : 10 20 30 40 50
Traversing using iterator 10 20 30 40 50