0% found this document useful (0 votes)
2 views

BCAMJ23402DS using C++ Object and Classes Unit 1

The document provides an overview of Object-Oriented Programming concepts in C++, focusing on objects and classes, including their definitions, examples, and usage. It explains access specifiers, constructors, destructors, and copy constructors, along with how to pass and return objects in functions. Various code examples illustrate the implementation of these concepts in C++.

Uploaded by

aditya.048001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

BCAMJ23402DS using C++ Object and Classes Unit 1

The document provides an overview of Object-Oriented Programming concepts in C++, focusing on objects and classes, including their definitions, examples, and usage. It explains access specifiers, constructors, destructors, and copy constructors, along with how to pass and return objects in functions. Various code examples illustrate the implementation of these concepts in C++.

Uploaded by

aditya.048001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Data Structure using C++

BCAMJ23402
Unit 1 [Object and Classes]

C++ Object

In C++, Object is a real-world entity, for example, chair, car, pen, mobile, laptop etc. In other
words, object is an entity that has state and behaviour. Here, state means data and behaviour
means functionality.
Object is a runtime entity; it is created at runtime. Object is an instance of a class. All the
members of the class can be accessed through object. Let's see an example to create object of
student class using s1 as the reference variable.

Student s1; //creating an object of Student

In this example, Student is the type and s1 is the reference variable that refers to the instance
of Student class.

C++ Class
In C++, object is a group of similar objects. It is a template from which objects are created. It
can have fields, methods, constructors etc.
Let's see an example of C++ class that has three fields only.
1. class Student
2. {
3. public:
4. int id; //field or data member
5. float salary; //field or data member
6. String name;//field or data member
7. };

C++ Object and Class Example


Let's see an example of class that has two fields: id and name. It creates instance of the class,
initializes the object and prints the object value.
1. #include <iostream>
2. using namespace std;
3. class Student
4. {
5. public:
6. int id;//data member (also instance variable)
7. string name;//data member(also instance variable)
8. };
9. int main()
10. {
11. Student s1; //creating an object of Student
12. s1.id = 201;
13. s1.name = "Sonoo Jaiswal";
14. cout<<s1.id<<endl;
15. cout<<s1.name<<endl;
1
16. return 0;
17. }

C++ Class Example: Initialize and Display data through method


Let's see another example of C++ class where we are initializing and displaying object
through method.
1. #include <iostream>
2. using namespace std;
3. class Student {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. void insert(int i, string n)
8. {
9. id = i;
10. name = n;
11. }
12. void display()
13. {
14. cout<<id<<" "<<name<<endl;
15. }
16. };
17. int main(void) {
18. Student s1; //creating an object of Student
19. Student s2; //creating an object of Student
20. s1.insert(201, "Sonoo");
21. s2.insert(202, "Nakul");
22. s1.display();
23. s2.display();
24. return 0;
25. }

C++ Class Example: Store and Display Employee Information


Let's see another example of C++ class where we are storing and displaying employee
information using method.
1. #include <iostream>
2. using namespace std;
3. class Employee {
4. public:
5. int id;//data member (also instance variable)
6. string name;//data member(also instance variable)
7. float salary;
8. void insert(int i, string n, float s)
9. {
10. id = i;
11. name = n;
12. salary = s;
13. }
14. void display()
15. {
16. cout<<id<<" "<<name<<" "<<salary<<endl;

2
17. }
18. };
19. int main(void) {
20. Employee e1; //creating an object of Employee
21. Employee e2; //creating an object of Employee
22. e1.insert(201, "Sonoo",990000);
23. e2.insert(202, "Nakul", 29000);
24. e1.display();
25. e2.display();
26. return 0;
27. }

Same employee example with private Section


#include <iostream>
using namespace std;
class Employee
{
private:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
public:
void insert(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main()
{
Employee e1; //creating an object of Employee
Employee e2; //creating an object of Employee
Employee e3;
e1.insert(201, "Sonoo",990000);
e2.insert(202, "Nakul", 29000);
e1.display();
e2.display();
return 0;
}

Scope resolution operator in C++


In C++, scope resolution operator is ::. It is used for following purposes.

1) To access a global variable when there is a local variable with same name:
// C++ program to show that we can access a global variable
// using scope resolution operator :: when there is a local
// variable with same name
3
#include<iostream>
using namespace std;
int x; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Output:
Value of global x is 0
Value of local x is 10

2) To define a function outside a class.


// C++ program to show that scope resolution operator :: is used
// to define a function outside a class
#include<iostream>
using namespace std;
class A
{
public:
// Only declaration
void fun();
};
// Definition outside class using ::
void A::fun()
{
cout << "fun() called";
}
int main()
{
A a;
a.fun();
return 0;
}
Output:
fun() called

Access Specifiers

Visibility modes can be classified into three categories:

4
o Public: When the member is declared as public, it is accessible to all the functions of
the program. Members declared public can be accessed from anywhere (inside or
outside the class). It allows unrestricted access.
o Private: When the member is declared as private, it is accessible within the class only.
Members declared private can only be accessed inside the class. They cannot be
accessed directly from outside the class.
o Protected: When the member is declared as protected, it is accessible within its own
class as well as the class immediately derived from it. Members declared protected act
like private but can be accessed in derived (child) classes. Used mainly for
inheritance.

Visibility of Inherited Members

Base class visibility Derived class visibility

Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected

Comparison Table
Access Accessible Inside Accessible Outside Accessible in Derived
Specifier Class Class Class
public ✅ Yes ✅ Yes ✅ Yes
private ✅ Yes ❌ No ❌ No
protected ✅ Yes ❌ No ✅ Yes

Constructor
In C++, constructor is a special method which is invoked automatically at the time of object
creation. It is used to initialize the data members of new object generally. The constructor in
C++ has the same name as class.
5
There can be two types of constructors in C++.
o Default constructor
o Parameterized constructor
Default Constructor
A constructor which has no argument is known as default constructor. It is invoked at the
time of creating object.
Let's see the simple example of C++ default Constructor.
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Default Constructor Invoked"<<endl;
9. }
10. };
11. int main(void)
12. {
13. Employee e1; //creating an object of Employee
14. Employee e2;
15. return 0;
16. }

C++ Parameterized Constructor


A constructor which has parameters is called parameterized constructor. It is used to provide
different values to distinct objects. Let's see the simple example of C++ Parameterized
Constructor.

#include<iostream>
using namespace std;
class Employee
{
public:
int id;//data member (also instance variable)
string name;//data member(also instance variable)
float salary;
Employee(int i, string n, float s)
{
id = i;
name = n;
salary = s;
}
void display()
{
cout<<id<<" "<<name<<" "<<salary<<endl;
}
};
int main(void)
{
Employee e1 =Employee(101, "Sonoo", 890000); //creating an object of Employee
Employee e2(102, "Nakul", 59000);

6
e1.display();
e2.display();
return 0;
}

Destructor
A destructor works opposite to constructor; it destructs the objects of classes. It can be defined
only once in a class. Like constructors, it is invoked automatically. A destructor is defined like
constructor. It must have same name as class. But it is prefixed with a tilde sign (~).

Constructor and Destructor Example


Let's see an example of constructor and destructor in C++ which is called automatically.
1. #include <iostream>
2. using namespace std;
3. class Employee
4. {
5. public:
6. Employee()
7. {
8. cout<<"Constructor Invoked"<<endl;
9. }
10. ~Employee()
11. {
12. cout<<"Destructor Invoked"<<endl;
13. }
14. };
15. int main(void)
16. {
17. Employee e1; //creating an object of Employee
18. Employee e2; //creating an object of Employee
19. return 0;
20. }

Output:
Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

Copy Constructor
A Copy constructor is an overloaded constructor used to declare and initialize an object from
another object.

Syntax Of User-defined Copy Constructor

Class_name(const class_name &old_object);

Consider the following situation:


1. class A
2. {
3. A(A &x) // copy constructor.
4. {
7
5. // copyconstructor.
6. }
7. }

In the above case, copy constructor can be called in the following ways:

Let's see a simple example of the copy constructor.

// program of the copy constructor.


1. #include <iostream>
2. using namespace std;
3. class A
4. {
5. public:
6. int x;
7. A(int a) // parameterized constructor.
8. {
9. x=a;
10. }
11. A(A &i) // copy constructor
12. {
13. x = i.x;
14. }
15. };
16. int main()
17. {
18. A a1(20); // Calling the parameterized constructor.
19. A a2(a1); // Calling the copy constructor.
20. cout<<a2.x;
21. return 0;
22. }

Output:
20

When Copy Constructor is called

Copy Constructor is called in the following scenarios:


o When we initialize the object with another existing object of the same class type. For
example, Student s1 = s2, where Student is the class.
o When the object of the same class type is passed by value as an argument.
o When the function returns the object of the same class type by value.

Passing and Returning Objects in C++

In C++ we can pass class’s objects as arguments and also return them from a function the
same way we pass and return other variables. No special keyword or header file is required
to do so.
Passing an Object as argument

8
To pass an object as an argument we write the object name as the argument while calling
the function the same way we do it for other variables.
Syntax:
function_name(object_name);
Example: In this Example there is a class which has an integer variable ‘a’ and a function
‘add’ which takes an object as argument. The function is called by one object and takes
another as an argument. Inside the function, the integer value of the argument object is added
to that on which the ‘add’ function is called. In this method, we can pass objects as an
argument and alter them.
// C++ program to show passing
// of objects to a function

#include <iostream>
using namespace std;

class Example {
public:
int a;
// This function will take
// an object as an argument
void add(Example E)
{
a = a + E.a;
}
};

// Driver Code
int main()
{
// Create objects
Example E1, E2;
// Values are initialized for both objects
E1.a = 50;
E2.a = 100;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n";
// Passing object as an argument
// to function add()
E2.add(E1);
// Changed values after passing
// object as argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a
<< "\n& object 2: " << E2.a
<< "\n\n";
return 0;
}
Output
Initial Values
Value of object 1: 50

9
& object 2: 100

New values
Value of object 1: 50
& object 2: 150

Returning Object as argument


Syntax:
object = return object_name;
Example: In the above example we can see that the add function does not return any value
since its return-type is void. In the following program the add function returns an object of
type ‘Example'(i.e., class name) whose value is stored in E3.
In this example, we can see both the things that are how we can pass the objects as well as
return them. When the object E3 calls the add function it passes the other two objects
namely E1 & E2 as arguments. Inside the function, another object is declared which
calculates the sum of all the three variables and returns it to E3.
This code and the above code is almost the same, the only difference is that this time the
add function returns an object whose value is stored in another object of the same class
‘Example’ E3. Here the value of E1 is displayed by object1, the value of E2 by object2 and
value of E3 by object3.

// C++ program to show passing


// of objects to a function
#include <iostream>
using namespace std;
class Example {
public:
int a;

// This function will take


// object as arguments and
// return object
Example add(Example Ea, Example Eb)
{
Example Ec;
Ec.a = Ea.a + Eb.a;
// returning the object
return Ec;
}
};
int main()
{
Example E1, E2, E3;
// Values are initialized
// for both objects
E1.a = 50;
E2.a = 100;
E3.a = 0;
cout << "Initial Values \n";
cout << "Value of object 1: " << E1.a
<< ", \nobject 2: " << E2.a
<< ", \nobject 3: " << E3.a

10
<< "\n";
// Passing object as an argument
// to function add()
E3 = E3.add(E1, E2);
// Changed values after
// passing object as an argument
cout << "New values \n";
cout << "Value of object 1: " << E1.a
<< ", \nobject 2: " << E2.a
<< ", \nobject 3: " << E3.a
<< "\n";
return 0;
}
Output
Initial Values
Value of object 1: 50,
object 2: 100,
object 3: 0
New values
Value of object 1: 50,
object 2: 100,
object 3: 150

Static Data Member and Static Member Function in C++


In C++, the static keyword is used to define static data members and static member
functions inside a class. These members belong to the class rather than to an instance
(object) of the class.

1. Static Data Member


 A static data member is a variable that is shared by all objects of a class.
 It is declared inside the class but defined outside the class using the scope
resolution operator ::.
 It is initialized only once and retains its value throughout the program.
 It can be accessed using class name (ClassName::staticVariable) or through an
object.
Example: Static Data Member

#include <iostream>
using namespace std;
class Student {
public:
string name;
int rollNo;
static int count; // Declaration of static data member
// Constructor to increment count when a new student is created
Student(string n, int r)
{
name = n;
rollNo = r;
count++; // Increments for each new object
}
void display()

11
{
cout << "Name: " << name << ", Roll No: " << rollNo << endl;
}
};

// Definition of static data member outside the class


int Student::count = 0;
int main() {
Student s1("Alice", 101);
Student s2("Bob", 102);
s1.display();
s2.display();
// Accessing static data member using class name
cout << "Total Students: " << Student::count << endl;
return 0;
}
Output:
Name: Alice, Roll No: 101
Name: Bob, Roll No: 102
Total Students: 2

Key Points About Static Data Members:


✔ Shared by all objects of the class.
✔ Defined outside the class with ::.
✔ Initialized only once (default value = 0 for int).
✔ Can be accessed using class name (Student::count) or object (s1.count).

2. Static Member Function


 A static member function is a function that can access only static members of the
class.
 It does not need an object to be called; it can be called using the class name.
 It cannot access non-static members (since non-static members belong to
individual objects).
Example: Static Member Function
#include <iostream>
using namespace std;
class Student {
public:
string name;
int rollNo;
static int count; // Static data member
Student(string n, int r) {
name = n;
rollNo = r;
count++;
}
void display() {
cout << "Name: " << name << ", Roll No: " << rollNo << endl;
}
// Static member function
static void showCount() {
cout << "Total Students: " << count << endl;
12
// cout << name; // ❌ ERROR: Cannot access non-static members
}
};

// Definition of static data member


int Student::count = 0;
int main() {
Student s1("Alice", 101);
Student s2("Bob", 102);
s1.display();
s2.display();
// Calling static function using class name
Student::showCount();
return 0;
}
Output:
Name: Alice, Roll No: 101
Name: Bob, Roll No: 102
Total Students: 2

Key Points About Static Member Functions:


✔ Can access only static members.
✔ Cannot access non-static data members.
✔ Can be called without creating an object using ClassName::FunctionName().

Abstract Class in C++


An abstract class in C++ is a class that cannot be instantiated and is designed to be
inherited by other classes. It serves as a base class and contains at least one pure virtual
function.

What is a Pure Virtual Function?


A pure virtual function is a function that must be overridden in derived classes. It is
declared using = 0 syntax.
Syntax:

class AbstractClass { public: virtual void pureVirtualFunction() = 0; // Pure virtual function


};

Example: Abstract Class in C++


#include <iostream>
using namespace std;
// Abstract class (contains a pure virtual function)
class Shape {
public:
virtual void area() = 0; // Pure virtual function
void display() {
cout << "This is a shape." << endl;
}
};

// Derived class (implements pure virtual function)


class Circle : public Shape {
13
private:
float radius;
public:
Circle(float r) { radius = r; }
void area() override { // Overriding pure virtual function
cout << "Circle Area: " << 3.14 * radius * radius << endl;
}
};

// Derived class (implements pure virtual function)


class Rectangle : public Shape {
private:
float length, width;
public:
Rectangle(float l, float w) { length = l; width = w; }
void area() override { // Overriding pure virtual function
cout << "Rectangle Area: " << length * width << endl;
}
};

int main() {
// Shape s; // ❌ Error: Cannot instantiate abstract class
Circle c(5.0);
Rectangle r(4.0, 6.0);
c.area(); // Calls overridden function in Circle
r.area(); // Calls overridden function in Rectangle
return 0;
}
Output:
Circle Area: 78.5
Rectangle Area: 24

Key Points About Abstract Classes


1. Cannot be instantiated:
o Shape s; ❌ (Error: Object of abstract class cannot be created)
2. Must have at least one pure virtual function:
o virtual void area() = 0;
3. Derived classes must override pure virtual functions:
o If a derived class does not override all pure virtual functions, it remains
abstract.
4. Can have regular functions:
o void display() { cout << "This is a shape."; }
o Derived classes inherit and can use these functions.

C++ Friend function


If a function is defined as a friend function in C++, then the protected and private data
of a class can be accessed using the function. By using the keyword friend compiler knows
the given function is a friend function. For accessing the data, the declaration of a friend
function should be done inside the body of a class starting with the keyword friend.
Declaration of friend function in C++.
1. class class_name
2. {
14
3. friend data_type function_name(argument/s); // syntax of friend function.
4. };

In the above declaration, the friend function is preceded by the keyword friend. The function
can be defined anywhere in the program like a normal C++ function. The function definition
does not use either the keyword friend or scope resolution operator.

Characteristics of a Friend function:


o The function is not in the scope of the class to which it has been declared as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name and dot
membership operator with the member name.
o It can be declared either in the private or the public part.
C++ friend function Example
Let's see the simple example of C++ friend function used to print the length of a box.
1. #include <iostream>
2. using namespace std;
3. class Box
4. {
5. private:
6. int length;
7. public:
8. Box(): length(0) { }
9. friend int printLength(Box); //friend function
10. };
11. int printLength(Box b)
12. {
13. b.length += 10;
14. return b.length;
15. }
16. int main()
17. {
18. Box b;
19. cout<<"Length of box: "<< printLength(b)<<endl;
20. return 0;
21. }
Output:
Length of box: 10
Let's see a simple example when the function is friendly to two classes.
1. #include <iostream>
2. using namespace std;
3. class B; // forward declarartion.
4. class A
5. {
6. int x;
7. public:
8. void setdata(int i)
9. {
10. x=i;
11. }
12. friend void min(A,B); // friend function.

15
13. };
14. class B
15. {
16. int y;
17. public:
18. void setdata(int i)
19. {
20. y=i;
21. }
22. friend void min(A,B); // friend function
23. };
24. void min(A a,B b)
25. {
26. if(a.x<=b.y)
27. scout << a.x << endl;
28. else
29. cout << b.y << endl;
30. }
31. int main()
32. {
33. A a;
34. B b;
35. a.setdata(10);
36. b.setdata(20);
37. min(a,b);
38. return 0;
39. }

Output:
10
In the above example, min() function is friendly to two classes, i.e., the min() function can
access the private members of both the classes A and B.

C++ Friend class


A friend class can access both private and protected members of the class in which it has
been declared as friend.
Let's see a simple example of a friend class.
#include <iostream>
using namespace std;
class A
{
int x;
friend class B; // friend class.
public:
A():x(5){}
};
class B
{
public:
void display(A &a)
{
cout<<"value of x is : "<<a.x;

16
}
};
int main()
{
A a;
B b;
b.display(a);
return 0;
}
Output:
value of x is : 5
In the above example, class B is declared as a friend inside the class A. Therefore, B is a
friend of class A. Class B can access the private members of class A.

Source
1. C++ Programming Language - GeeksforGeeks
2. C++ Tutorial | Learn C++
3. C++ Tutorial | Learn C++ Programming for Beginners - Tpoint Tech

17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy