L3 Classes
L3 Classes
Declaring
Synatx:
Objects ClassName ObjectName;
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int speed;
Objects of };
int main() {
the Class Car myCar;
Car myCar.brand = "Toyota";
myCar.speed = 120;
cout << "Brand: " << myCar.brand << endl;
cout << "Speed: " << myCar.speed << " km/h" << endl;
return 0;
}
#include <iostream>
using namespace std;
class Car {
public:
string brand;
int speed;
Objects of };
int main() {
the Class Car myCar;
Car myCar.brand = "Toyota";
myCar.speed = 120;
cout << "Brand: " << myCar.brand << endl;
cout << "Speed: " << myCar.speed << " km/h" << endl;
return 0;
}
Relationship
between a Class &
Object
By default, the members of a class are private.
Private data members and private functions can
be accessed only by member functions of a
Cont… class.
Public members can be accessed from outside
of the class.
Member functions define the behavior of a class. They can be
defined inside or outside the class.
In Class definition;
ObjectName.MemberFunction ();
Member function can be defined in two ways:
1. Inside the class: When a member function is
defined inside a class, it is considered to be
inline by default.
Defining 2. Outside the class. Inside Class: When a
function is large then it should be defined
Member outside the class declaration.
return_type Class_Name
:: function_Name;
class Sample {
private:
int num;
void setNum(int n) {
num = n;
Nesting of }
public:
Member
void display() {
Functions setNum(10); // Calling another member
function
cout << "Number: " << num << endl;
}
};
Access Specifiers
• Access specifiers control how class members (variables and functions) can be
accessed:
1. public – Accessible from outside the class.
2. private – Accessible only within the class.
3. protected – Accessible within the class and derived (child) classes.
class Test {
private:
int x; // Private member
public:
void setX(int val) { // Public member function
x = val;
Example }
int getX() {
return x;
}
};
#include <iostream> // Use standard iostream
using namespace std; // Avoid prefixing std::
class student {
private:
char name[80];
Example int rn;
float marks;
student }
cout << "Name: " << name << "\nRoll No: " << rn << "\nMarks: " << marks << endl;
a: 10
b: 20
A parameterized constructor accepts arguments to initialize
an object.
class Car {
public:
string brand;
Car(string b) {
brand = b;
Parameterized cout << "Brand: " << brand << endl;
Constructor }
};
int main() {
Car myCar("Toyota");
return 0;
}
Destructor