A class is created using the class
keyword followed by its name and members enclosed in curly braces. An object is an instance of the class, created by declaring a variable of the class type.
Objects and classes are the building blocks that allow us to model real-world entities in code. A class is a template, and objects are the actual things made from it. For example, consider a "Car" in the real world. Each car has attributes like color, model, and engine capacity, and behaviors like driving and braking. In programming, we use classes to define these attributes and behaviors, and objects represent individual cars, such as "Red Tesla Model S."
Classes and objects help:
They allow us to translate real-world scenarios into code.
Once a class is created, we can reuse it to create multiple objects.
By grouping related data and methods, classes make programs more readable and maintainable.
A class in C++ is a user-defined data type that encapsulates
Now that we know what a class is, let’s see how to define one in C++.
class ClassName {public:// Data members (attributes)int dataMember;// Member functions (methods)void memberFunction() {// Function body}};
Imagine you're designing a library system. You’ll need a way to represent each book with its title, author, and ISBN. That’s where classes come in!
Let's write down a complete code in example below:
#include <iostream>using namespace std;class Book {public:// Data membersstring title;string author;string ISBN;// Member functionvoid displayDetails() {cout << "Title: " << title << endl;cout << "Author: " << author << endl;cout << "ISBN: " << ISBN << endl;}};int main() {// Creating an object of the Book classBook myBook;// Assigning values to the object's data membersmyBook.title = "The Great Gatsby";myBook.author = "F. Scott Fitzgerald";myBook.ISBN = "9780743273565";// Calling a member functionmyBook.displayDetails();return 0;}
An object is an instance of a class. While a class defines the structure and behavior, the object represents a specific entity based on that structure.
ClassName objectName;
For example:
Book myBook;
Data members: Variables defined inside a class that hold data specific to objects (e.g., title
, author
).
Member functions: Methods defined inside a class that operate on data members (e.g., displayDetails()
).
Access specifiers control how data members and member functions of a class can be accessed. Let's explore one by one:
Public: Members declared as public are accessible from outside the class.
Private: Members declared as private can only be accessed within the class itself. By default, class members are private in C++.
Protected: Members declared as protected are accessible within the class and its derived classes.
Example:
class Example {private:int privateData; // Only accessible within the classpublic:int publicData; // Accessible from outside the classprotected:int protectedData; // Accessible within the class and its derived classes};
Constructors are special member functions that run automatically when an object is created. They are used to initialize an object's data members.
Types of constructors:
Default Constructor: A constructor that does not take any arguments. It initializes the object with default values.
Parameterized Constructor: A constructor that takes arguments to initialize the object with specific values.
Example
class Book {public:// Default constructorBook() {title = "Unknown";author = "Unknown";}// Parameterized constructorBook(string t, string a) {title = t;author = a;}};
Let’s revisit the "Book" class with an additional feature to borrow a book.
#include <iostream>#include <string>using namespace std;// Define the Book classclass Book {public:string title;string author;bool isAvailable;// ConstructorBook(string t, string a) {title = t;author = a;isAvailable = true; // Book is initially available}// Member function to issue the bookvoid issueBook() {if (isAvailable) {isAvailable = false;cout << "The book \"" << title << "\" has been issued." << endl;} else {cout << "Sorry, the book \"" << title << "\" is already issued." << endl;}}// Member function to return the bookvoid returnBook() {// Write your code}};int main() {// Create a Book objectBook myBook("The C++ Guide", "John Doe");// Test the issueBook() functionmyBook.issueBook();// Test the returnBook() functionmyBook.returnBook();// Test returning an already available bookmyBook.returnBook();return 0;}
Try it: Modify the Book
class to include a returnBook()
function on line 30 that marks the book as available again. Create an object and test this functionality.
Classes and objects are foundational concepts in OOP, allowing you to model real-world scenarios in code.
A class is a blueprint, while an object is an instance of that blueprint.
Data members store attributes, and member functions define behavior.
Syntax for creating classes and objects is straightforward but powerful for organizing and managing code.
Practicing with real-world examples like the "Book" class helps solidify understanding and application of these concepts.
Start your programming journey with our Learn C++ Course. This course offers step-by-step guidance, hands-on examples, and practical exercises to help you build a strong foundation in C++. Looking to go from beginner to expert? Explore the Become a C++ Programmer Path. This skill path covers everything from the basics of C++ to advanced programming concepts, with the skills needed to excel in real-world projects.
Haven’t found what you were looking for? Contact Us