C++ / Object-Oriented Programming in C++

Working with Classes and Objects

In this tutorial, we'll explore how to work with classes and objects in C++. You'll learn about creating classes, instantiating objects, and using these objects.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Covers OOP principles such as classes, objects, inheritance, and polymorphism.

Working with Classes and Objects in C++

Introduction

In this C++ tutorial, we will learn about the fundamental concept of object-oriented programming, i.e., classes and objects. Classes are the blueprint of objects, and objects are instances of classes. We will understand the process of defining classes, creating objects, and manipulating these objects.

By the end of this tutorial, you will learn:
- What are classes and objects?
- How to define a class?
- How to create and use objects?

Prerequisites: Basic knowledge of C++ programming.

Step-by-Step Guide

Classes in C++

A class is a user-defined data type that we can use in our program, and it works as an object constructor, or a "blueprint" for creating objects. A class is defined using the keyword class, followed by the class name.

class ClassName {
  // class body
};

Objects in C++

An object is an instance of a class. When a class is defined, only the specification for the object is defined; no memory or storage is allocated. To use the data and access functions defined in the class, you need to create objects.

ClassName objectName;

Member Variables and Functions

A class contains both variables (attributes) and functions/methods.

class Car {
   public:
      string brand;   // attribute
      int year;  // attribute
      void honk() {   // method
         cout << "Beep beep!\n";
      }
};

Code Examples

Example 1: Creating a Class and an Object

#include <iostream>
#include <string>
using namespace std;

// Define a class
class Car {
   public:
      string brand;   
      int year;
};

int main() {
   // Create an object of Car
   Car carObj1;
   carObj1.brand = "Toyota";
   carObj1.year = 2015;

   // Access attributes and display the value
   cout << carObj1.brand << " " << carObj1.year << "\n";

   return 0;
}

In the above example, we first define a Car class with two attributes: brand and year. Then, we create an object carObj1 for the Car class and assign values to its attributes. Finally, we display these attribute values.

Expected Output: Toyota 2015

Summary

In this tutorial, we learned about classes and objects in C++. We defined a class using the class keyword and created objects to access the data members and functions. We also learned how to access these members and functions using the dot operator (.).

Next steps for learning include understanding concepts like constructors, destructors, and inheritance in C++. For additional resources, refer to C++ Documentation.

Practice Exercises

  1. Exercise 1: Define a class Person with two attributes: name and age. Create an object of Person, set its attribute values and display them.

  2. Exercise 2: Add a function birthday() to the Person class that increases the age by 1 when called. Create an object, increase its age using the function, and display its new age.

Solutions

  1. Solution to Exercise 1
#include <iostream>
#include <string>
using namespace std;

// Define class Person
class Person {
   public:
      string name;   
      int age;
};

int main() {
   // Create an object of Person
   Person personObj;
   personObj.name = "John";
   personObj.age = 25;

   // Access attributes and display the value
   cout << personObj.name << " " << personObj.age << "\n";

   return 0;
}
  1. Solution to Exercise 2
#include <iostream>
#include <string>
using namespace std;

// Define class Person
class Person {
   public:
      string name;   
      int age;
      void birthday() {
         age++;
      }
};

int main() {
   // Create an object of Person
   Person personObj;
   personObj.name = "John";
   personObj.age = 25;

   // Call birthday method
   personObj.birthday();

   // Access attributes and display the value
   cout << personObj.name << " " << personObj.age << "\n"; // Expect "John 26"

   return 0;
}

In the second exercise, we've added a birthday() function to the Person class that increases the age by 1 when it's called. We then called this function on our personObj to increase its age before displaying it.

Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

Fake User Profile Generator

Generate fake user profiles with names, emails, and more.

Use tool

JWT Decoder

Decode and validate JSON Web Tokens (JWT).

Use tool

Image Converter

Convert between different image formats.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help