C++ Introduction
1. Classes and Objects
A class is a blueprint for creating objects (instances).
•Class defines data members (variables) and member functions (methods).
•Objects are instances of classes.
#include <iostream>
using namespace std;
class Student {
int roll;
string name;
public:
void setData(int r, string n) {
roll = r;
name = n;
}
void display() {
cout << "Roll: " << roll << ", Name: " << name << endl;
}
};
int main() {
Student s1, s2;
s1.setData(1, "Rahul");
s2.setData(2, "Priya");
s1.display();
s2.display();
return 0;
}
Output:
Roll: 1, Name: Rahul
Roll: 2, Name: Priya
Function Overloading
Function Overloading allows multiple functions with the
same name but different parameter lists.
Q1: Write a program to create a class Student with attributes roll and name. Take input for 3 students and display their details.
Q2: Create a class BankAccount with attributes accountNumber, holderName, and balance.
•Add functions to deposit money, withdraw money, and display account details.
Q3: Create a class Car with attributes:
•brand, model, price
Q4: C++ Program to Calculate the Area and Perimeter of a
Rectangle using Class and Objects
#include <iostream>
using namespace std;
class Math {
public:
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
};
int main() {
Math m;
cout << "Int Add: " << m.add(10, 20) << endl;
cout << "Double Add: " << m.add(2.5, 3.7) << endl;
return 0;
}
Int Add: 30
Double Add: 6.2