Classes, Objects, and
Member Functions
Introduction
•C++ is an Object-Oriented Programming language.
•Everything in C++ revolves around classes and objects.
•Helps in modeling real-world entities into programs.
What is a Class?
•A class is a user-defined data type.
•It defines data members and functions that operate on that data.
•Acts as a blueprint for objects.
Syntax of a Class
• class ClassName {
• public:
• int data;
• void display() {
• cout << data;
• }
• };
Example of a Class
• class Student {
• public:
• string name;
• int rollNo;
• void showData() {
• cout << "Name: " << name << ", Roll No: " << rollNo;
• }
• };
What is an Object?
•An object is an instance of a class.
•It represents a specific entity with unique data.
•Each object has its own copy of data members.
Creating an Object
• Student s1; // Object of class Student
• [Link] = "Ali";
• [Link] = 12;
• [Link]();
Accessing Members
• Use the dot (.) operator to access class members.
• [Link];
Member Functions
•Functions that belong to a class.
•Used to define behavior of the class.
•Can be defined:
[Link] the class
[Link] the class
Inside Class Definition
• class Car {
• public:
• void start() {
• cout << "Car Started!";
• }
• };
Outside Class Definition
• class Car {
• public:
• void start();
• };
• void Car::start() {
• cout << "Car Started!";
• }
Inline Functions
• Functions defined inside the class are inline by default.
• Faster execution for small, frequently used functions.
Access Specifiers
•Public: Accessible from anywhere.
•Private: Accessible only inside the class.
•Protected: Accessible in derived classes.
Specifier Accessibility
public Everywhere
private Within class
protected Derived classes
Example Program
• #include <iostream>
• using namespace std;
• class Student {
• private:
• int rollNo;
• public:
• void setRoll(int r) { rollNo = r; }
• void showRoll() { cout << "Roll No: " << rollNo; }
• };
• int main() {
• Student s1;
• [Link](10);
• [Link]();
• }
Summary
•Class → Template or blueprint
•Object → Instance of a class
•Member functions define object behavior
•Access specifiers control visibility