C++_Assignment_Teacher_Style
C++_Assignment_Teacher_Style
Name: Dipanshi
Course: ECE, 5th Semester
1. Polymorphism
Polymorphism allows a single function, operator, or object to behave differently in
different contexts. In C++, this is implemented as compile-time polymorphism (e.g.,
function overloading) or runtime polymorphism (e.g., virtual functions).
#include <iostream.h>
#include <conio.h>
class Shape {
public:
virtual void draw() { // Virtual function
cout << "Drawing a Shape";
}
};
void main() {
Shape *shape;
Circle circle;
shape = &circle;
shape->draw(); // Runtime polymorphism
getch();
}
2. Inline Function
An inline function is a function expanded at the point where it is called. It is useful to
reduce function call overhead for small, frequently used functions.
#include <iostream.h>
#include <conio.h>
void main() {
cout << "Square of 5: " << square(5);
getch();
}
3. Operator Overloading
Operator overloading enables operators to work with user-defined data types, like
objects, to extend their functionality.
#include <iostream.h>
#include <conio.h>
class Complex {
private:
float real, imag;
public:
Complex(float r = 0, float i = 0) {
real = r; imag = i;
}
Complex operator + (Complex c) {
return Complex(real + c.real, imag + c.imag);
}
void display() {
cout << real << " + " << imag << "i";
}
};
void main() {
Complex c1(2.5, 3.5), c2(1.5, 2.5), c3;
c3 = c1 + c2;
c3.display();
getch();
}
4. Constructor Overloading
Constructor overloading is defining multiple constructors in a class with different
parameter lists, allowing various ways to initialize objects.
#include <iostream.h>
#include <conio.h>
class Rectangle {
private:
int length, width;
public:
Rectangle() {
length = 0; width = 0;
}
Rectangle(int l, int w) {
length = l; width = w;
}
void display() {
cout << "Length: " << length << ", Width: " << width;
}
};
void main() {
Rectangle r1, r2(10, 20);
r1.display();
r2.display();
getch();
}
5. Call by Reference
Call by reference allows a function to directly access and modify the original
variable by passing its memory address.
#include <iostream.h>
#include <conio.h>
void main() {
int a = 10, b = 20;
cout << "Before Swap: a = " << a << ", b = " << b;
swap(a, b);
cout << "After Swap: a = " << a << ", b = " << b;
getch();
}