C++ Concepts Explained With Programs
C++ Concepts Explained With Programs
Programs
1. Constant vs Non-constant Functions
A constant function in C++ is a function that does not modify any member variables of the
class.
It ensures that the state of the object remains unchanged. To declare a constant function,
the 'const' keyword is used after the function declaration.
Constant functions are used when you want to guarantee that a function does not alter the
object's state.
This is particularly useful for functions that only retrieve data without modifying it.
Program Example
#include <iostream>
class Example {
int x;
public:
Example(int a) : x(a) {}
int getX() const { // Constant function
return x;
}
void setX(int a) { // Non-constant function
x = a;
}
};
int main() {
Example obj(10);
std::cout << "Value of x: " << obj.getX() << std::endl;
obj.setX(20);
std::cout << "Updated value of x: " << obj.getX() << std::endl;
return 0;
}
Static data members are class variables that are shared by all objects of the class.
They are not tied to any specific object. Static functions, similarly, are functions that can
access only static data members and do not depend on a particular object.
Static members and functions are used when some properties or behaviors are common to
all instances of a class.
They allow memory efficiency and are useful in counting objects or tracking common
values.
Program Example
#include <iostream>
class StaticExample {
static int count;
public:
StaticExample() { count++; }
static int getCount() { return count; }
};
int StaticExample::count = 0;
int main() {
StaticExample obj1, obj2, obj3;
std::cout << "Total objects created: " << StaticExample::getCount() << std::endl;
return 0;
}
Function overloading allows multiple functions with the same name but different
parameters.
Operator overloading enables you to redefine the behavior of an operator (like +, -, *) for
user-defined types.
Uses and Purpose
Program Example
// Function Overloading
#include <iostream>
class OverloadExample {
public:
void display(int i) {
std::cout << "Integer: " << i << std::endl;
}
void display(double f) {
std::cout << "Float: " << f << std::endl;
}
};
// Operator Overloading
class Complex {
int real, imag;
public:
Complex(int r = 0, int i = 0) : real(r), imag(i) {}
Complex operator + (Complex const &obj) {
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void display() {
std::cout << real << " + i" << imag << std::endl;
}
};
int main() {
OverloadExample obj;
obj.display(5);
obj.display(5.5);
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.display();
return 0;
}
5. Composition
In composition, one class contains an object of another class.
6. Aggregation
Aggregation is a weaker relationship where one class can reference another without
ownership.
7. Generic Programming
It allows writing flexible and reusable code, mostly using templates.