Curriculum
Course: Learn C++
Login

Curriculum

Learn C++

Text lesson

Creating Classes and Objects in C++

n this lesson, you will learn

  • Understanding the Classes and Objects
  • Understanding the Class Diagram
  • Examples: Creating Classes
  • Creating Multiple Classes

 

What is a Class?

  • A class is a blueprint or a prototype for creating objects (instances of the class).
  • It defines a data structure by bundling data members (variables) and methods (functions) that operate on the data.

ClassInC++

 

Example

A dog is a class that defines characteristics like color, length, height, weight, breed, etc., and behaviors like jumping, barking, sleeping, walking, shaking, etc.

These characteristics are known as the member variables, and the behavior is specified by functions.

Objectandclass

 

Syntax to Define a Class

class ClassName {
    // Access specifier (public, private, protected)
public:
    // Data members (attributes)
    int dataMember;

    // Member functions (methods)
    void memberFunction() {
        // Function body
    }
};

 

Access Specifiers: These control the visibility of class members. Common access specifiers include:

  • public: Members are accessible from outside the class.
  • private: Members are only accessible from within the class.
  • protected: Similar to private, but also accessible in derived classes.

 

What is an Object?

An object is an instance of a class. When you create an object, you allocate memory for it, and it can use the class’s data members and functions.

Example

A dog has states — color, name, breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.

ClassandObject

 

Syntax to Create an Object

ClassName objectName;

 

What is a Class Diagram

The UML or Class diagram is a graphical notation used to construct and visualize object oriented systems. A class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system’s:

  • classes,
  • their attributes (or Properties),
  • operations (or methods),
  • and the relationships among objects.

 

UML Class Notation

A class represent a concept which encapsulates state (attributes) and behavior (operations). Each attribute has a type. Each operation has a signatureThe class name is the only mandatory information.

UML Diagram

Class Name: The name of the class appears in the first partition.

Class Attributes: Attributes are shown in the second partition and attribute type is shown after the colon.

Class Operations (Methods): Operations are shown in the third partition knows as the services the class provides. The return type of a method is shown after the colon at the end of the method signature.

Class Visibility: + denotes public attributes or operations. The – denotes private attributes or operations. The # denotes protected attributes or operations.

 

Example 1: Creating a Class and Object

Let’s create a simple class called Rectangle that has a data members(length and width) and a member function displayDimensions.

#include<iostream>
using namespace std;

class Rectangle {
public:
    //Data members
    double length;
    double width;

    //Member function to display dimensions
    void displayDimensions() {
        cout<<"Length: "<< length;
        cout<<", Width: "<< width << endl;
    }
};

int main() {
    // Create an objects of the Rectangle class
    Rectangle rect1,rect2;

    // Set the length, and width of rectnagle 1
    rect1.length = 5;
    rect1.width = 6;

    // Set the length, and width of rectnagle 2
    rect2.length = 10;
    rect2.width = 20;

    // Call the member function
    cout<<"Rectangle 1 dimensions: "<<endl;
    rect1.displayDimensions();
    cout<<"Rectangle 2 dimensions: "<<endl;
    rect2.displayDimensions();

    return 0;
}


Output:

Rectangle 1 dimensions: 
Length: 5, Width: 6
Rectangle 2 dimensions:
Length: 10, Width: 20


 

Explanation

Data Members (length and width): These are variables that belong to the class. Every object of this class will have its own copy of length and width.

Member Functions (displayDimensions()): This function operates on the data members of the class. The displayDimensions() diplsay the dimensins of rectangles.

Object Creation (Rectangle rect1): Here, rect1 and rect2 are two different objects of the Rectangle class. Each object has its own length and width, and they are independent of each other.

Calling Member Functions (rect1.displayDimensions() ): We call the member functions displayDimensions() on rect1 to calculate the area and perimeter.

 

Example 2: Class with Multiple Data Members and Methods

Let’s create a more detailed class called Rectangle that includes two data members length and width, and member functions to calculate the area and perimeter.

#include 
using namespace std;

class Rectangle {
private:
    // Data members
    double length;
    double width;

public:
    // Member function to set dimensions
    void setDimensions(double l, double w) {
        length = l;
        width = w;
    }

    // Member function to calculate area
    double area() {
        return length * width;
    }

    // Member function to calculate perimeter
    double perimeter() {
        return 2 * (length + width);
    }

    // Member function to display dimensions
    void displayDimensions() {
        cout << "Length: " << length << ", Width: " << width << endl;
    }
};

int main() {
    // Create an object of the class Rectangle
    Rectangle myRectangle;

    // Set the dimensions of the rectangle
    myRectangle.setDimensions(5.0, 3.0);

    // Display dimensions
    myRectangle.displayDimensions();

    // Calculate and display the area and perimeter
    cout << "Area: " << myRectangle.area() << endl;
    cout << "Perimeter: " << myRectangle.perimeter() << endl;

    return 0;
}



Output:

Length: 5, Width: 3
Area: 15
Perimeter: 16


 

Example 3: Defining the Book Class

We’ll define a class named Book with data members to store the title, author, and number of pages of a book. We’ll also include member functions to set these values and to display the book details.

#include<iostream>
using namespace std;

class Book {
public:
    // Data members
    string title;
    string author;
    int pages;

    // Member function to set the book details
    void setDetails(string t, string a, int p) {
        title = t;
        author = a;
        pages = p;
    }

    // Member function to display the book details
    void displayDetails() {
        cout << "Title: " << title << endl;
        cout << "Author: " << author << endl;
        cout << "Pages: " << pages << endl;
    }
};

int main() {
    // Create the first Book object
    Book book1;
    book1.setDetails("The Catcher in the Rye", "J.D. Salinger", 277);

    // Create the second Book object
    Book book2;
    book2.setDetails("To Kill a Mockingbird", "Harper Lee", 281);

    // Display the details of book1
    cout << "Details of book1:" << endl;
    book1.displayDetails();

    // Display the details of book2
    cout << "Details of book2:" << endl;
    book2.displayDetails();

    return 0;
}


Output:

Details of book1:
Title: The Catcher in the Rye
Author: J.D. Salinger
Pages: 277
Details of book2:
Title: To Kill a Mockingbird
Author: Harper Lee
Pages: 281


 

Creating Multiple Classes

Creating multiple classes in C++ is straightforward. You can define as many classes as you need, each with its own data members and member functions. The classes can interact with each other in various ways, depending on the relationships you want to model

Example 1: Creating Two Independent Classes

In this example, we’ll define two independent classes: Book and Author. These classes don’t interact with each other directly.

#include<iostream>
using namespace std;

// Define the Book class
class Book {
public:
    string title;
    int pages;

    void setDetails(string t, int p) {
        title = t;
        pages = p;
    }

    void displayDetails() {
        cout << "Book Title: " << title << endl;
        cout << "Pages: " << pages << endl;
    }
};

// Define the Author class
class Author {
public:
    string name;
    int age;

    void setDetails(string n, int a) {
        name = n;
        age = a;
    }

    void displayDetails() {
        cout << "Author Name: " << name << endl;
        cout << "Age: " << age << endl;
    }
};

int main() {
    // Create an object of the Book class
    Book book1;
    book1.setDetails("1984", 328);

    // Create an object of the Author class
    Author author1;
    author1.setDetails("George Orwell", 46);

    // Display details of book1
    cout << "Book Details:" << endl;
    book1.displayDetails();

    // Display details of author1
    cout << "Author Details:" << endl;
    author1.displayDetails();

    return 0;
}


Output:

Book Details:
Book Title: 1984
Pages: 328
Author Details:
Author Name: George Orwell
Age: 46


Explanation:

  • Two Independent Classes (Book and Author): Here, Book and Author are independent classes. Each class has its own data members and member functions.
  • Objects of Each Class: We create objects book1 of the Book class and author1 of the Author class. They function independently, and we use them to set and display details separately.

 

Example 2: Creating Classes with Relationships (Composition)

In this example, we’ll define a relationship between two classes. The Library class will contain objects of the Book class, demonstrating a composition relationship.

#include<iostream>
using namespace std;

// Define the Book class
class Book {
public:
    string title;
    int pages;

    void setDetails(string t, int p) {
        title = t;
        pages = p;
    }

    void displayDetails() {
        cout << "Book Title: " << title << endl;
        cout << "Pages: " << pages << endl;
    }
};

// Define the Library class
class Library {
public:
    string name;
    Book book1;  // Library has a Book object
    Book book2;  // Library has another Book object

    void setLibraryDetails(string n, Book b1, Book b2) {
        name = n;
        book1 = b1;
        book2 = b2;
    }

    void displayLibraryDetails() {
        cout << "Library Name: " << name << endl;
        cout << "Books in the Library:" << endl;
        book1.displayDetails();
        book2.displayDetails();
    }
};

int main() {
    // Create Book objects
    Book book1;
    book1.setDetails("1984", 328);

    Book book2;
    book2.setDetails("To Kill a Mockingbird", 281);

    // Create a Library object
    Library lib;
    lib.setLibraryDetails("Central Library", book1, book2);

    // Display Library details
    lib.displayLibraryDetails();

    return 0;
}


Output:

Library Name: Central Library
Books in the Library:
Book Title: 1984
Pages: 328
Book Title: To Kill a Mockingbird
Pages: 281

 

Explanation:

  • Composition Relationship: The Library class has two Book objects (book1 and book2). This illustrates a composition relationship where the Library class is composed of Book objects.
  • Setting and Displaying Details: We first create Book objects and then pass them to the Library class. The Library class can then display the details of the books it contains.

 


End of the lesson….enjoy learning

 

 

Student Ratings and Reviews

 

4.0
4.0 out of 5 stars (based on 4 reviews)
Excellent75%
Very good0%
Average0%
Poor0%
Terrible25%

 

 

October 2, 2024

good

September 20, 2024

good

September 2, 2024

well explained

August 30, 2024

very very impt topic.

 

 

Submit a Review

 

 


Warning: Undefined array key "student_url_profile" in /var/www/wp-content/plugins/masterstudy-lms-learning-management-system/_core/lms/helpers.php on line 1340

Warning: Undefined array key "student_url_profile" in /var/www/wp-content/plugins/masterstudy-lms-learning-management-system/_core/lms/helpers.php on line 1345