What Is a Class?
o Think of a class as a blueprint for something you want to create—like a blueprint
for a house.
o A blueprint tells you what the house should look like (rooms, doors, windows) but
it is not the actual house you can live in.
2. In Programming
o In C++, a class is a template that describes:
▪ Data (which we often call “attributes” or “member variables”).
▪ Actions (which we often call “member functions” or “methods”).
3. Why Use Classes?
o They help you organize your code by grouping together related data and the
functions that operate on that data.
o They make code easier to reuse and maintain.
Example (Conceptual, No C++ Code)
• Class: CarBlueprint might describe what attributes a car has (color, brand, model, year) and
what it can do (drive, brake, honk).
• But CarBlueprint itself is not a car—it’s just the design.
What Is an Object?
o If a class is like a blueprint, an object is like the actual house that’s built from
that blueprint.
o You can build multiple houses from the same blueprint, each with its own
address, paint color, furniture, etc.
2. In Programming
o In C++, an object is an instance of a class—that means it’s a real, usable thing
in your program.
o Each object has its own copies of the data specified in the class.
Example (Conceptual, No C++ Code)
• Using the CarBlueprint example: if you have:
o Car car1, Car car2, Car car3
o Each car object has its own brand, color, year, etc.
o Each can “drive,” “brake,” or “honk,” independently of the others.
Key Differences
1. Default Access Specifiers
o Class: private by default.
o Struct: public by default.
2. Conventional Usage
o Class: used for complex objects, encourages encapsulation (private data + public
methods).
o Struct: used for simpler data grouping, often with minimal or no encapsulation.
3. Object: Not a type definition, but a specific instance of either a class or a struct.
Summary
• A class in C++ is a blueprint that defines how an entity is structured and how it
behaves.
• An object is a concrete instance of that class, with its own set of data.
• A struct is very similar to a class but has public members by default and is often used for
simpler data structures.
Constructor
1. What Is a Constructor?
o A constructor is a special member function in a class that automatically
executes when you create (instantiate) an object.
o It has the same name as the class.
o It has no return type (not even void).
2. Why Do We Need a Constructor?
o Initialize the object’s data (e.g., set default values for variables).
o Prepare any resources the object needs (e.g., opening a file, allocating memory,
etc.).
3. Types of Constructors
o Default Constructor: Takes no parameters or all parameters have default values.
o Parameterized Constructor: Accepts parameters to initialize the object with
specific values.
o Copy Constructor: Creates a new object as a copy of an existing object (e.g.,
Car(const Car &other)).
What They Do
o
A constructor is a special function that runs automatically when you create a
new object (like Car car1;).
o It initializes the object’s data (for example, sets default values or assigns specific
values you pass in).
2. Why They Are Important
o Ease of Use: You don’t have to remember to manually set all the variables
correctly for each new object. The constructor does this for you in one place.
o Clean, Organized Code: Instead of having to call multiple “set” functions after
creating an object, you just call Car myCar("Honda", "Civic", 2020); and everything is
set up right away.
o Prevents Errors: By automatically assigning valid initial values, you reduce the
chance of bugs caused by uninitialized variables.
class Car {
private:
string brand;
string model;
int year;
public:
// Parameterized constructor
Car(const string& b, const string& m, int y) {
brand = b;
model = m;
year = y;
}
};
// Usage:
Car car1("Toyota", "Corolla", 2020);
Here, you don’t need to write separate lines like:
car1.brand = "Toyota";
car1.model = "Corolla";
car1.year = 2020;
The constructor takes care of that in one step.
Destructor
1. What Is a Destructor?
o
A destructor is a special member function in a class that automatically executes
when the object is about to be destroyed.
o It has the same name as the class but with a tilde (~) in front.
o It cannot take parameters and cannot return any value.
2. Why Do We Need a Destructor?
o To clean up resources the object was using (e.g., close files, release memory).
o Ensures no resource leaks remain once the object’s lifetime ends (e.g., when it
goes out of scope or is deleted).
Aspect Constructor Destructor
Purpose Initialize object’s data and Clean up or release resources
resources
Name Same as class (e.g., Car()) Tilde + class name (e.g., ~Car())
Parameters Can have parameters (or none) No parameters allowed
Return Type None (not even void) None (not even void)
Call Time Called automatically when Called automatically when
object is created object is destroyed
Constructors get your object “ready to use” by initializing data or allocating resources.
Destructors ensure everything is cleaned up properly when the object is done being used.
In most C++ programs, you’ll define a constructor to set up the object and, if you allocate
resources manually (e.g., with new), you’ll often define a destructor to avoid memory leaks or
other resource issues.
1. What They Do
o A destructor is a special function that runs automatically when an object is
about to be destroyed (for example, when it goes out of scope or you call delete on
a dynamically allocated object).
o It frees or cleans up anything the object was using, such as memory, files, or
network connections.
2. Why They Are Important
o Prevents Resource Leaks: If you allocated memory, opened files, or used other
system resources in your constructor (or elsewhere), the destructor ensures those
resources get released properly (so you don’t “lose” them, causing a memory leak
or a file handle leak).
o Automates Cleanup: You don’t have to remember to call a “cleanup” function—
C++ calls the destructor for you at the right time.
o Keeps Code Safe: By pairing construction (setting up resources) with
destruction (freeing resources), you ensure your program behaves predictably
and doesn’t waste resources.
1. class Car {
2. private:
3. string* brandPtr; // Let's say we allocate memory for brand
4.
5. public:
6. // Constructor: allocate memory and set brand
7. Car(const string& b) {
8. brandPtr = new string(b);
9. }
10.
11. // Destructor: free memory
12. ~Car() {
13. delete brandPtr;
14. }
15. };
When you create a Car object, you allocate memory.
When the object is no longer needed, the destructor is called, freeing that memory automatically.
Constructors and destructors work hand-in-hand:
1. Constructor: “I need to set up or allocate the stuff this object needs.”
2. Object Lives: You use the object in your program.
3. Destructor: “I need to release or clean up the stuff I allocated.”
This pattern keeps your code organized, safe, and efficient, ensuring that every resource you
acquire (in the constructor or elsewhere) is eventually released (in the destructor).
What Is Inheritance?
o Think of inheritance in terms of a family: a child “inherits” certain traits (like eye
color or hair color) from a parent.
o In C++, a derived class (the child) inherits methods and attributes from a base
class (the parent).
2. Definition in C++
o Inheritance allows you to reuse and extend the functionality of an existing class
(the base or parent class) by creating a derived or child class.
o The derived class gets all the non-private members (data and functions) of the
base class and can add its own new members or override existing ones.
3. Why Use Inheritance?
o Code Reusability: You don’t have to rewrite code that’s already in the base class.
o Organization: Common features go in the base class, specialized features go in
derived classes.
o Extend Functionality: The derived class can add new behaviors or modify
existing ones.
Base Class and Derived Class
1. Base Class
o The class whose members (attributes, methods) are being inherited.
o Also called the parent or superclass.
2. Derived Class
o The class that inherits from the base class.
o Also called the child or subclass.
o Can add or redefine (override) certain methods.
class BaseClass {
public:
// Public data members
// Public methods
protected:
// Protected data members
// Protected methods
private:
// Private data members (not inherited directly)
};
class DerivedClass : public BaseClass {
public:
// Additional data members or methods
// Overridden methods (if any)
};
: public BaseClass means public inheritance (the most common type).
If you see : protected BaseClass or : private BaseClass, that changes how members are accessed
in the derived class, but for beginners, public inheritance is the main one to focus on.
What Is Encapsulation?
1. Simple Definition
o Encapsulation means putting data (variables) and the functions (methods)
that work on that data together in one place—which is usually a class.
o It also means keeping some parts “hidden” (private) so that people using your
class can’t directly mess with it in unintended ways.
2. Analogy (Pill Capsule)
o Picture a medicine capsule. It hides the powder or liquid inside (the data).
o You only see the outside of the capsule. If you need medicine, you swallow the
capsule, but you don’t open it and directly handle the medicine inside.
o In programming, encapsulation is similar: other parts of the program don’t see
the inside of the “capsule.” They just use public methods to get or change the data
safely.
3. Key Benefits
o Protects Data: By making data private, you prevent accidental (or malicious)
changes.
o Easier to Maintain: If the data changes, you only update the inside of the class.
All other code can continue using the same public methods.
o Control Access: You decide how and when data is accessed or modified.
Encapsulation in C++
1. Private Members
o Variables or functions declared as private cannot be accessed outside the class.
This is like hiding them inside the “capsule.”
2. Public Members
o Functions (and possibly some variables) declared as public can be accessed from
anywhere. These are like the opening that you provide to the outside world.
3. Getters & Setters
o You might provide “getter” methods (like getName()) that safely return the value of
a private variable, and “setter” methods (like setName(...)) that safely change it.
o This way, you can include checks or extra logic when someone tries to read or
write the data.
Encapsulation is about hiding data and only exposing what’s necessary through public methods.
It keeps your code clean, safe, and modular.
In C++, we achieve encapsulation by making most data private and providing public getters and setters,
along with any other methods needed to interact with the data in a controlled way.