Class 10 | Class and Object | C++ Notes

C++ Classes

A class is the collection of similar objects which is defined as the blueprint to define attributes and behavior for all the objects of the class.

Syntax:

class class-name {
variable;
function;
};

Object

An object is a real-world entity having data and methods.

Syntax:

class-name object-name;

Access Specifier

In C++, access specifiers are keywords used to control the access levels of class members.

They determine how different parts of a program can interact with the members of a class.

There are three main access specifiers in C++:

1. Private

Members declared as private are accessible only within the same class or from friend functions.

They are not accessible from outside the class, including derived classes.

This specifier is used to hide the internal details of a class and to provide encapsulation.

2. Protected

Protected members are mainly used during inheritance.

Members declared as protected are accessible within the same class, from derived classes, and from friend functions.

They are not accessible from outside the class hierarchy.

3. Public

Members declared as public are accessible from anywhere in the program.

They can be accessed through an object of the class using the dot operator.

Accessing Data Members of a Class

Access to a data member depends upon the access control of that member.

If the access control is public, the data member can be easily accessed using the member access or dot operator (.) with the object of the class.

If the data member is defined as private or protected, we cannot access the data member directly.

Example: Accessing Data Member Using Public Access Control

#include <iostream>

class MyClass {

public:

int NepalEnotes;

};

int main() {

MyClass obj;

obj.NepalEnotes = 10;

std::cout << “Value of publicMember: ” << obj.NepalEnotes << std::endl;

return 0;

}

Example: Accessing Data Member Using Private Access Control

#include <iostream>

class nepalEnotes {

private:

int nexus;

public:

void setNexus(int value) {

nexus = value;

}

int getNexus()

{

return nexus;

}

};

int main() {

nepalEnotes nexus;

nexus.setNexus(10);

std::cout << “Value of nexus: ” << nexus.getNexus() << std::endl;

return 0;

}

Example: Accessing Data Member Using Protected Access Control

#include <iostream>

using namespace std;

class nepalEnotes {

protected:

int nexus;

public:

void setNexus(int value) {

nexus = value;

}

int getNexus()

{

return nexus;

}

};

int main() {

nepalEnotes nexus;

nexus.setNexus(10);

cout << “Value of nexus: ” << nexus.getNexus() << endl;

return 0;

}

Defining Member Function

Member functions are functions having their declarations inside the class definition and work on the data members of the class.

There are two ways to define member functions:

  1. Defining member function inside the class
  2. Defining member function outside the class

1. Defining Member Function Inside the Class

These functions are defined within the class definition and provide the ability to perform operations on the class’s data members and interact with other objects of the same class.

Arguments can also be passed within the function.

Syntax:

return-type function-name(set of arguments with data types)

{

function body;

}

Example: Defining Member Function Inside the Class

#include <iostream>

using namespace std;

class NepalEnotes {

public:

// Member function definition inside the class

void NexuCorner() {

cout << “Keep Learning From The Best Platform” << endl;

}

};

int main() {

NepalEnotes obj;

// Calling the member function NexuCorner inside the class

obj.NexuCorner();

return 0;

}

2. Defining Member Function Outside the Class

If a member function’s definition is outside the class declaration, it is treated as an inline function only if it is explicitly declared as inline.

The function name in the definition must be qualified with its class name using the scope-resolution operator (::).

Syntax:

Return_type class_name :: function_name(parameter_list)

{

function body;

}

Example: Defining Member Function Outside the Class

#include <iostream>

using namespace std;

// Class declaration

class NepalEnotes {

public:

// Function declaration

void NexuCorner();

};

// Function definition outside the class

void NepalEnotes::NexuCorner() {

cout << “Keep Learning From The Best Platform” << endl;

}

int main() {

NepalEnotes obj;

// Calling the member function

obj.NexuCorner();

return 0;

}

C++ Program to Enter Details of Student Using OOP Concept

#include <iostream>
#include <string>

using namespace std;

class DurgaLaxmi {

private:

string name;
int rollNumber;
float fee;
string studentClass;
string studentID;

public:

// Member function to set student details

void setDetails(string n, int rn, float f, string cl, string id) {

name = n;
rollNumber = rn;
fee = f;
studentClass = cl;
studentID = id;

}

// Member function to print student details

void NepalEnotes() {

cout << “Student Name: ” << name << endl;
cout << “Roll Number: ” << rollNumber << endl;
cout << “Fee: $” << fee << endl;
cout << “Class: ” << studentClass << endl;
cout << “Student ID: ” << studentID << endl;

}

};

int main() {

DurgaLaxmi NexuCorner;

// Setting student details using member function

NexuCorner.setDetails(“John Doe”, 101, 500.0, “Grade 10”, “STU123”);

// Calling the member function NepalEnotes to print student details

NexuCorner.NepalEnotes();

return 0;

}

Constructor

A constructor in C++ is a special member function of a class that is automatically called when an object of that class is created.

Its primary purpose is to initialize the object’s data members and perform any necessary setup tasks.

Constructors have the same name as the class and have no return type, not even void.

It is used to create value for an object.

Characteristics of Constructor

Same Name as Class

Constructors have the same name as the class they belong to.

No Return Type

Constructors do not have a return type, not even void.

Called Automatically

Constructors are automatically called when an object of the class is created.

Initialization

Constructors are primarily used for initializing the object’s data members and performing necessary setup tasks.

Can Be Overloaded

Like regular functions, constructors can be overloaded.

This means a class can have multiple constructors with different parameter lists.

Can Have Default Arguments

Constructors can have default arguments, allowing objects to be created with fewer arguments if needed.

Cannot Be Inherited or Overridden

Constructors cannot be inherited or overridden by derived classes.

However, derived class constructors can call base class constructors.

No Explicit Return

Constructors do not have an explicit return statement.

Once the constructor finishes execution, the object is considered initialized and ready for use.

Invoked Implicitly

Constructors are invoked implicitly when an object is created using the class name and optional arguments.

Initialization Lists

Constructors can use initialization lists to initialize data members directly.

This can be more efficient than assignment in the body of the constructor.

Can Be Private

Constructors can be made private to prevent direct instantiation of objects, enforcing singleton or factory patterns.

Types of Constructor

There are three types of constructors:

  1. Default Constructor
  2. Parameterized Constructor
  3. Copy Constructor

1. Default Constructor

A default constructor in C++ is a constructor that does not take any arguments.

It is called automatically when an object of the class is created without providing any initial values.

Default constructors are provided by the compiler if no other constructors are explicitly defined in the class.

Syntax:

class ClassName {

public:

// Default Constructor

ClassName() {

// Initialization code

}

};

Example: Default Constructor

#include <iostream>

using namespace std;

class NepalEnotes {

public:

// Default Constructor

NepalEnotes() {

cout << “Nepal E-notes Platform For Easy And Effective Learning” << endl;

}

};

int main() {

// Creating an object of class NepalEnotes obj;

return 0;

}

2. Parameterized Constructor

A parameterized constructor is a constructor in object-oriented programming that allows you to initialize an object with specific values when it is created.

It takes parameters as input and assigns those values to the instance variables of the object.

This enables you to create objects with different initial states depending on the values passed to the constructor.

Syntax:

class ClassName {

public:

// Parameterized constructor declaration

ClassName(type1 parameter1, type2 parameter2, …) {

// Constructor body

// Initialization of instance variables using parameters

}

};

Example: Parameterized Constructor

#include <iostream>
#include <string>

using namespace std;

class NepalEnotes {

private:

string officeName;
string location;
int numOfEmployees;

public:

// Parameterized constructor

NepalEnotes(string name, string loc, int employees) {

officeName = name;
location = loc;
numOfEmployees = employees;

}

// Member function to display office details

void Nexus() {

cout << “Office Name: ” << officeName << endl;
cout << “Location: ” << location << endl;
cout << “Number of Employees: ” << numOfEmployees << endl;

}

};

int main() {

// Creating an object using the parameterized constructor

NepalEnotes office(“Nepal Enotes Pvt. Ltd.”, “Attariya”, 50);

// Displaying office details using the member function

cout << “Office Details:\n”;

office.Nexus();

return 0;

}

3. Copy Constructor

A copy constructor in C++ is a special constructor that initializes a new object as a copy of an existing object.

It is invoked when a new object is created and initialized with the data of an existing object of the same class.

The copy constructor allows you to create a new object with the same data as the existing object.

Syntax:

class ClassName {

public:

// Copy constructor declaration

ClassName(ClassName &obj)

{

variable1 = obj.variable1;
variable2 = obj.variable2;
variable n = obj.variable n;

}

};

Example: Copy Constructor

#include <iostream>
#include <string>

using namespace std;

class NepalEnotes {

private:

string message;

public:

// Default constructor

NepalEnotes() : message(“Be The Best By learning from the best”) {}

// Parameterized constructor

NepalEnotes(string msg) : message(msg) {}

// Copy constructor

NepalEnotes(NepalEnotes& other) : message(other.message) {}

// Member function Nexus

void Nexus() {

cout << “Nexus function called. Message: ” << message << endl;

}

// Member function Nexu

void Nexu() {

cout << “Nexu function called. Message: ” << message << endl;

}

};

int main() {

// Create an object

NepalEnotes obj1;

// Call Nexus function

obj1.Nexus();

// Create another object using copy constructor

NepalEnotes obj2 = obj1;

// Call Nexu function on the second object

obj2.Nexu();

return 0;

}

Constructor Overloading

Constructor overloading in C++ refers to the ability to define multiple constructors for a class, each with a different set of parameters.

This allows objects of the class to be initialized in different ways depending on the parameters passed during object creation.

Constructor overloading provides flexibility in object initialization and can make code more readable and maintainable.

Example: Constructor Overloading

#include <iostream>
#include <string>

using namespace std;

class DurgaLaxmi {

private:

string message;

public:

// Default constructor

DurgaLaxmi() {

message = “Default Message”;

}

// Parameterized constructor

DurgaLaxmi(string msg) {

message = msg;

}

// Copy constructor

DurgaLaxmi(DurgaLaxmi& other) {

message = other.message;

}

// Member function Nepal

void Nepal() {

cout << “Nepal function called. Message: ” << message << endl;

}

};

int main() {

// Using default constructor

DurgaLaxmi obj1;

obj1.Nepal();

// Using parameterized constructor

DurgaLaxmi obj2(“Be The Best By learning from the best”);

obj2.Nepal();

// Using copy constructor

DurgaLaxmi obj3 = obj2;

obj3.Nepal();

return 0;

}

Destructor

A destructor is a special member function of a class that is automatically called when an object goes out of scope or is explicitly deleted using the delete keyword.

The destructor has the same name as the class preceded by a tilde (~) symbol.

It is used to release resources acquired by the object during its lifetime, such as:

  • Dynamic memory allocations
  • File handles
  • Database connections
  • Other resources

Syntax:

class ClassName {

public:

// Constructor, member functions, etc.

// Destructor declaration

~ClassName() {

// Destructor body

// Cleanup code

}

};

Example: Destructor

#include <iostream>

using namespace std;

class NexuCorner {

public:

// Constructor

NexuCorner() {

cout << “Constructor called” << endl;

}

// Destructor

~NexuCorner() {

cout << “Destructor called” << endl;

}

};

int main() {

cout << “Creating object…” << endl;

NexuCorner obj; // Constructor called

cout << “Object created.” << endl;

cout << “Exiting main…” << endl;

return 0;

}

Static Data Member

In C++, a static data member is a member of a class that belongs to the class itself rather than to individual objects of the class.

This means that there is only one instance of the static data member shared among all objects of the class.

It is declared using the static keyword within the class declaration.

Syntax:

class ClassName {

public:

static data_type staticDataMemberName;

};

Example: Static Data Member

#include <iostream>

using namespace std;

class NepalEnotes {

public:

static int count; // Declaration of static data member

NepalEnotes() {

count++; // Increment count each time an object is created

}

static void Nexus() {

cout << “Nexus function called. Count: ” << count << endl;

}

};

int NepalEnotes::count = 0; // Definition and initialization of static data member

int main() {

NepalEnotes obj1;
NepalEnotes obj2;
NepalEnotes obj3;

NepalEnotes::Nexus(); // Call static function Nexus

return 0;

}

Static Member Function

A static member function is a member function of a class that operates on class-level data rather than on specific objects of the class.

It does not have access to the this pointer, meaning it cannot access non-static member variables or call non-static member functions directly.

Static member functions are called using the class name, not an object of the class.

They are declared using the static keyword within the class declaration.

Syntax:

class ClassName {

public:

static return_type functionName(parameters);

};

Example: Static Member Function

#include <iostream>

using namespace std;

class NepalEnotes {

private:

static int count;

public:

static void Nexus() {

cout << “Nexus function called. Count: ” << count << endl;

}

static void incrementCount() {

count++;

}

};

// Definition and initialization of static data member

int NepalEnotes::count = 0;

int main() {

NepalEnotes::incrementCount();
NepalEnotes::incrementCount();
NepalEnotes::incrementCount();

NepalEnotes::Nexus();

return 0;

}

Discussion

Share a helpful question, idea, or explanation with other students.

Leave a Comment

Write a clear question, answer, or helpful explanation.
Your email will not be published.

Download Our Offline App

Study class-wise notes even when internet is not available. Get the app from Play Store.

Nepal eNotes offline app preview
Get it on Google Play