How to create classes and objects in C++

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."

Why do we need classes and objects?

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.

What is a class in C++?

A class in C++ is a user-defined data type that encapsulates data membersVariables defined inside a class that hold data specific to objects (e.g., title, author). (variables) and member functionsMethods defined inside a class that operate on data members (e.g., displayDetails()). (methods). It serves as a template to create objects. Think of a class as a template for a library—it defines what a library should look like, but it’s not a library itself.

Now that we know what a class is, let’s see how to define one in C++.

Syntax of class 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:

Code example in C++

#include <iostream>
using namespace std;
class Book {
public:
// Data members
string title;
string author;
string ISBN;
// Member function
void displayDetails() {
cout << "Title: " << title << endl;
cout << "Author: " << author << endl;
cout << "ISBN: " << ISBN << endl;
}
};
int main() {
// Creating an object of the Book class
Book myBook;
// Assigning values to the object's data members
myBook.title = "The Great Gatsby";
myBook.author = "F. Scott Fitzgerald";
myBook.ISBN = "9780743273565";
// Calling a member function
myBook.displayDetails();
return 0;
}

What is an object in C++?

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.

Syntax of an object in C++

ClassName objectName;

For example:

Book myBook;

What are data members and member functions?

  • 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()).

What are access specifiers in class?

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 class
public:
int publicData; // Accessible from outside the class
protected:
int protectedData; // Accessible within the class and its derived classes
};
Access specifiers in C++

What are constructors in C++?

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:

  1. Default Constructor: A constructor that does not take any arguments. It initializes the object with default values.

  2. Parameterized Constructor: A constructor that takes arguments to initialize the object with specific values.

Example

class Book {
public:
// Default constructor
Book() {
title = "Unknown";
author = "Unknown";
}
// Parameterized constructor
Book(string t, string a) {
title = t;
author = a;
}
};
Constructors in C++

Let’s revisit the "Book" class with an additional feature to borrow a book.

Code example

#include <iostream>
#include <string>
using namespace std;
// Define the Book class
class Book {
public:
string title;
string author;
bool isAvailable;
// Constructor
Book(string t, string a) {
title = t;
author = a;
isAvailable = true; // Book is initially available
}
// Member function to issue the book
void 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 book
void returnBook() {
// Write your code
}
};
int main() {
// Create a Book object
Book myBook("The C++ Guide", "John Doe");
// Test the issueBook() function
myBook.issueBook();
// Test the returnBook() function
myBook.returnBook();
// Test returning an already available book
myBook.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.

Key takeaways

  • 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.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How do you create a class and object?

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.


How to create the object and access the class members?

Objects are created by declaring a variable of the class type. You can access public members of a class using the dot operator (.) with the object.


How to initialize an object in C++?

Objects can be initialized using constructors, which are special functions that initialize an object’s members upon creation. Alternatively, members can be directly assigned values using the dot operator after object creation.


How to declare a class in C++? Example?

A class is declared using the class keyword, followed by its name and members. Members can include variables and functions, categorized as public, private, or protected based on their access level.


Can I create an object inside a class?

Yes, an object of one class can be created inside another class to represent relationships. For self-referencing objects, pointers like this are used to avoid infinite recursion.


Free Resources