Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
25 views
22 pages
Classes and Object
Class and Object
Uploaded by
su9753
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save CLASSES AND OBJECT For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
25 views
22 pages
Classes and Object
Class and Object
Uploaded by
su9753
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save CLASSES AND OBJECT For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save CLASSES AND OBJECT For Later
You are on page 1
/ 22
Search
Fullscreen
2.1. INTRODUCTION In the previous chapter we learnt about the basic differences between C and C++, along with new features of C++. By the end of the first chapter we recalled the use of structures in C language. The knowledge of structures is very important to understand the ‘class’ concept in C++. Structure and class in C++ are almost similar but with only two basic differences out of which, one will be discussed in this chapter and the other is discussed in chapter 15, section 15.16. This chapter also deals with the working of ‘this’ pointer which is an internal pointer. Hence, before directly dwelling into the concept of classes and objects in C+, let us first clearly understand what is the drawback of structures in C and find the differences between structures in C and structures in C++. And after this, we shall discuss relationship between the structures in C++ and classes in C++. 2.2. STRUCTURES IN C Structures in C helps in binding (packing) logically related data of different or same data types together, Once the structure type is defined, we can create variables of that type using declaration statements (also a definition statement). For example, let us consider a simple program as below. Program 2.1 [e2siecaey| #include
struct simple ( int ay double b; he int main( ) { struct simple el, e2; el.a = 10; el.b = 20.0; e2.a=1; e2.b = 2.0; print£( “d\n%f\nsd\n%f\n", el.a, el.b, e2.a, e2.b )7return 0; } Output: 10 20.0 x 2.0 In the above program 2.1, Struct simple 4 int a; double b; he is the structure declaration, ‘The keyword struct creates a new data type « ’ can hold two clements ‘a’ and ‘b' of different data types. These elements ag Structure elements, But it should be noted that, structure declaration does ng allocate memory for its members. The memory is actually allocated once the. structure type is created. In the above program, in the main function, the statement, Struct simple el, e2; Creates two variables ‘el’ and ‘e2’ of type ‘struct simple’. At this point of va the memory is allocated for the structure members or elements ‘a’ and has its own copy of structure elements ‘a’ and ‘b’. This éan be pictorally Figure 2.1. struct simple inta double b [2 2 Figure 2.1(SRSSETENSmeasenant onsets - an rrtrevvction (7) ‘The statements, el.a = 10; el.b = 20.0; e2.a= 1; e2.b = 2.0; shows how the structure elements of each structure variables are assigned values using the dot operator () ot object to member access operator. That is, el.a= 10; says, assign the value 10, to the structure element ‘a’ belonging to the structure variable ‘el’. Similarly, e2.b= 2.0; says, assign the value 2.0 to the structure element ‘b’, belonging to the variable “ output of the program 2.1 can be understood easily by self analysis. Now, after learning to declare a structure, create its variables and assign values to its elements, let us understand the disadvantage of structures in C. For that, let us consider another program. Program 2.2 eon finclude
void funl( int, int ); /* Function prototype */ void fun2( int , int ); /* Function prototype */ struct simple { int a; int b; h struct simple el, €2; int main( ) A { funl( 5, 7 )7 fun2( 6, 8); print£( “Sd\ttd\téd\ttd\t”, el.a, el.b, e2.a, e2.b i. | return 0; sf } void fun1( int x, int y ) { vob el.a= xiel.bey ) void fun2( int x, int y ) ‘ e2.a=x; e2.b = ae } Output : es ob, 8 In the above program 2.2, two vatiables of type ‘struct simple’ ate crear, the previous Program, the structure elements are not acy assigned the Feo unctions ‘fanl() and ‘fun2() are called from the run)” Funetig functions initialize the value to the structure elements, And here lies the 4 Security. That is, in C structures, any function can modify the values Be said to be potty drawback in C structures, Other than the disadvantage that is discussed above there is another gi C structures, ‘That is, there is NO provision for functio: y re Particular structure and its data members, which Operates on the structure d t to be defined or declared inside the structure itself, In. other words, in © function definition cannot be Packed within a structure This can be shown with ad ns which are logic along with the d lummy piece of code, struct employee { int a; Get_salary( ) /+ { Not allowed in ¢ Structures “fi /* Function definition ie } rae If this concept were to be Provided in C structures then the Hacker Oca conic pete together and unrelated from Polluting the structure Vatiables, But this concept of pa structure declaration is not available in © language, .[RUNDE aes an onsets ~ An sntrodcrton (39) These disadvantages can be overcome by the structures in C++. 2.3. STRUCTURES IN C++ ‘struct’ keyword is redefined in C++. Let us first take up the example of structures in C++. Program 2.3 /*2.3.cpp */ #include
using namespace std; struct employee { int salary; int bonus; void get_salary( int age, int y ) { if ( age < 20) { salary = (y — ly /.2).)7 } else 1 salary = y } } int putusalary( ) 4) 9) { > 4 return salary; 3 } he a int main( ) { struct employee el, 627 , el.get_salary( 19, 10000 )7_ , e2.get salary( 22, 10000); ajc! \ 20) cout << el.put_salary( ) << endl; voasdenect cout << e2.put_salary( ) << endl; otdt A return 0; 0 } Output: 5000 10000Th In the above C44 Program, Struct employee int salary; int bonus; Void get_salary( int age, int y ) { if ( age < 20 ) { Salary = (y — (yi/)2).)7 else { salary = y; } int put_salary, ) { return salary; } Me is the structure declaration. And statement Struct employee el, e2 ; in the main(,) function creates two vatiables ‘et’ and “2? Pe ‘struct employee’. The important thing to no is th: at, the functions that ae logically related to t the structure itsel£ Recall that in Previous se definition or declaration within a steucture de This disadvantage of C structures is overcome The elements ‘salary’ and ‘bonus’ in the st, “enlrs and the functions ‘get_salary()’ and P of struct employee, Each object Copy of the data members, while of function definition, through can be pictorially represented as called objects of user tice in the above Structure. he structure elements are d ction, we had learnt that, the claration is not allowed in C by C++ structures, ‘ucture declaration are known a wtsalary()’ are known as memb ‘el’ and ‘€2” of the structure ‘employee’ h both the objects ‘el” and ‘e2', each share a: i ‘hich they can access or modify their data shown in Figure 2.2,senna ongeetseanmnerawcxso (2) struct employees int salary int bonus void get salary(); void put salary(); fel 2 } salary salary bonus Bord t | void get salary(){} int put salary() (} Figure 2.2 In the above program 2.3, each function definition in the structure is invoked or called from the main function using the object to member access operator; let us discuss clearly. To access the data members of the object ‘el” through member functions, we use the statements, el.get_salary( ); e2.put_salary( ); ‘ ‘The function definitions ‘get_salary() { ... }’ and ‘put_salary(){ ... }” gets invoked: with respect to the object ‘el’, to change/modify/access e1’s data members. It is important to note that, inside the function definition, the data members are not to use the dot operator preceding with the object name. Be! For example, int put_salary( ) {return el.salary; //object with dot operator not requireq // flashes error ) because, we have already invoked the member function using the object to operator i.e, using the statement like, el.put_salary( ); This automatically tells the compiler that, the function an wal] data members of object ‘el’. Hence no need of explicitly using the obj access operator again within the function definition. Similarly is the case with the object ‘e2”. So, the next question is “can 6 functions have access to or modify the data members of a structure?” The ‘The data members can be accessed from the main function also, provided, of object to member access operator is necessary. For example, ' Program 2.4 /*2.4.cpp */ #include
7 using namespace std; 1 struct employee { \ int salary; int bonus; void get_salary( int age, int y ) | 4 { if ( age < 20) { ‘ salary = (y- (y /2)); | i} else { salary = y; | ) ) int put_salary( ) ( return salary; y Mi } int main( ) { struct employee el, e2;Led es — el.get_salary( 19, 10000 ); e2.get_salary( 22, 10000 ); cout << el.put_salary( ) << endl; cout << e2.put_salary( ) << endl; el.salary = 8000; e2.salary = 9000; cout << el.salary << endl; cout << e2.salary << endl; return 0; ) Output: 5000 10000 8000 9000 In the above program, the data member ‘salary’ of both the obj accessed or modified from the main function, i., without ‘ovina of the structure, Now, if a non-member function like the ‘main( )’ can have acces value of the data member belonging to a structure, then how is the : member provided or guaranteed? How can we secure the data from. non-member functions. The answer is by using the acess specifiers visibility labels. 2.4. ACCESS SPECIFIERS There are three member access specifiers in C++. They are ext to implement the concept called data hiding, They are * private + public * protected Private: ‘A data member or member function that is declared as prite within the structure /class; which means only member functions can access the private data member of that structure class. The psi not accessible outside the class. They can be accessed by themer 5 private for a class, by, the data te oak jn next 86cm © in chapter 3) of this lass: BY 4 structure. The class concePt ® Public : tions that are ec the public secti The di bers at ‘anywhere within a Program, a gees Yeas decaraion qa beaten oye my fora last By the data members are public Jor Protected: ieclared in the pro ‘The data members and membet fear ane functions ad oe of a particular class can be accessed only BY oe ‘Tp the member functions ‘i lass, Also the protected members © i derived from that class. Itis not ac detail in the chapter 6. Please ignore this ifiers into wot z fee ram 2.5. at Let us’ put these acces practically. Check out the below pr0B! Program 2.5 /*2.5.cpp */ #include
using namespace std? | struct simple { private: int a7 { int b? public : int ¢ void set_data( int x, int y ) { i yi a b ) int get_data( ) { return (a+b); ) Ve * int main( ) {jem reaaaes and onsets - an rtvoaetton (8) struct simple e; e.set_data( 5, 5 ); cout << e.get_data( ) << endl; e.b = 203 // Error e.c = 307 // Correct return 0; In the above structure, the data members ‘a’ and ‘b’ are declared as private(note that very much mandatory aftet access specifiers), which means that, these data m ; can be accessed only by the member functions of the structure to which the data belongs. Hence, the function call e.set_data( ); e.get_data( ); are given permission to access the data members and are valid statements. statement 42081 the private data member of the ee structure, But the data above structure declaration is declared public. Therefore, ‘c’ can be access structure definition also. Hence the statement, = 30; in the ‘main()’ function is perfectly valid and allowed in C++. As stated e: the members of a structure are public. Program 2.6 /*2.6.cpp*/ finclude
using namespace std; struct simple { b int c7 // publi void set_data( int x, int y ) (oa a= x; b= yi } int get_data( ) *“return (a ¢ BI? Private: int a; " int b; int main( ‘ Struct simple e; ©-set_data( 5, 5 ); an Sout _<< e.get_data( ) << en (iieeor ‘ ee 14, Corkect i zero; - ) laced the strug Note: As sructisa keyword derived from C, C++ uses or replaced the « : by another keyword class The only difference eee a a ae by default the members of a class ate declared private an declared public, Hence from now on, lets start using the class keyword. Before that lets classes and objects, : 2.5. CLASSES A class isa basic building block of Object Oriented Programmi the data and its logically related functions together. A class is an abstract data i an be treated like any other builtin data type. A class definition has two parts, Class head * Class boay Class head 4 class name of class 1 Class body { os data members; member functions, Class head : Consists of keyword lass’ Followed by a user defined puma Class body; te — 23Consists of data members (either of pri cee nbers private, public, protected or any combination cach) ancl member function definition of decarition( ether of Private, public, eee or any combination of each ) with a opening brace '{‘ and a closing brace ‘}” bya semi colon *}. ‘An example class definition is as follows: class simple oi ( private : int a; int by public + float ¢; void set_data( int x, int y ) { ; a= x; Je } int get_data( ) { return (a +b); t he From the above example, ‘class’ is a keyword used to create a new abs ‘simple’ is the name of the class ( user-defined) , which forms the class declaration starts with an opening brace and ends with a closing’ a semicolon() as shown in the example. aj private( followed by : Jand public( followed by :) are known as ae modifiers, which decide the accessibility of data members of the cli functions and non-member functions of the class ‘simple’. ‘a’ and members, both of type ‘int’ which can be accessed only by the cla ‘c’is the public data member of type float that can be accessed fi program. ‘The data members can be of any data type. The data m initialized within the class declarations. It can be initialized only (discussed in detail in chapter 5) once the object of that class is creat Characteristics of member functions + A member function’s name is invisible outside the class, are declared within the scope of its class. 4A member function can be defined inside the class oF outside yy Scope resolution operator ). A member function can have access to private, protected and public Of the its class, but cannot access private data members of another 2-6. OBJECTS IN C++ Objects are the variables of classes. Object is an instance of a class, An, abstraction of real world entity. It has a set of data and functions, thar Once a class is defined, we can create any numbet of objects of that class j declaration just gives a template of the data and functions. The memory fog members are allocated only once the class object is defined or created, The Creating objects is known as instantiation. The syntax for declaring objects jg
,
,....
sing namespace std; ass largest private: int a7 int by public : void input_data( int x, int y ) { a= x; b-y ) int big( ) { " if (a>b) return a; else return b; M int main( ) { largest 17 // ‘1! igs an object of class largest int a, b7 cout << “Enter the two numbers “ << endl; cin >> a >> bs l.input_data( a, b); //calling the class member function using // object and dot operator cout << The largest number is “ << 1.big( ) << endl; return 07 } 2.7. CHARACTERISTICS OF ACCESS SPECIFIERS( PRIVATE, PUBLIC AND PROTECTED) The characteristics of access specifiers are as follows: + private section of a class can have both the data members and member functions, but usually data members are made private for data security.| Example: Class a Example: t Private : int a; int put_data( )7 Public: int ¢; int get_data( ); he Itis not mandatory that, private section has to oe ae =e cau the public section. It can be done in the reverse class A { Public : int c; int get_data( ); private int a; int put_data( ); If no member access specifier or modifier is specified, then, by defaule are private for the class. class A { int a; //private by default int put_data( );//private by default public: int cf int get_data( ); There may be any number of private, public or protected declaration.protected access modifier or specifier is used for declaring the lass : ss s and its derived class.(protected access SP ecifier is tan be accessed by its own cla explained in detail in chapter 6 ). HOW TO DEFINE A FUNCTION OUTSIDE A CLASS 7 aa > ‘ ). But Till now we have seen, the definition of a function inside the class declaration. e : be define a member function of a class outside the class declaration. Yes. Tt can function has to be 28. can we gone using the scope resolution operator (2). But the prototype of the ‘within the class declaration. ‘The syntax is as follows:
; :
( ) / member function definition ) where, |_type — return type of the function_name() 'ss_name > The class to which the function_name is a member function function_name —» The name of the member function of a class class_name. Let us write a program to understand this. Program 2.8 * 2.8.cpp */ finclude
using namespace std7 class simple int aj int b; public: int add( int , int // prototype of the member function, i =| int simple :: add( int x, int y) //member function definition outside //the class.i Phe! fe ont int main( ) ‘ simple e ; : cout << e.add( 5, 10) << endl 7 return 0 ; ) Output : 15 In the above program, the function definition for ‘add()’ is as follows, int simple :: add( int x, int y) { int bs z-atb; return z ; 2 y As shown above, the function ‘add ()) is defined outside the class | resolution operator (: ). The scope resolution operator tells the scope function belongs. In other words, in the above function definition, the Operator (:) says that, the function ‘add,’ belongs to the class ‘simple? outside the class declaration. INITIALIZATION OF VARIABLES IN C++ In C++, the initialization of variables is done in way we initialize in C language using equal (=)sign, Ex: int i= 16; ‘The other way is as shown in the example below Ex: int i(16);‘The second form is like that because. all built -in data types are consideted as classes and the variables of these data types are treated as objects. 0. THE ARROW OPERATOR ‘The arrow (->) operator is also called as pointer to member access operator. The arrow operator is used when member functions or member data has to be accessed through a pointer which is pointing to an object of a class, ot in other sense, when a pointer contains the address of the object of a particular class ‘The general form for using arrow operator is as follows: pointer_to_object->class member; Check out the following program 2.9 to understand how arrow ‘operator works. Program 2.9 finclude
using namespace std; class simple int a7 int b, public: int 7 int add( int, int ); simple add( int x, int y ) xr b=yi return (a+b 3 t main( ) int sum; simple e; sum = e.add( 6, 5 )7 cout << sum << endl; e.c = 10; cout << e.c << endl; simple *el = 6e; sum = el->add( 5, 25 )i cout << sum << endl; // accessing the class member using // arrow operatorss member using Arrow oa e1->c = 20;//accessing the ©) cout << el->c << endl return 0; ) Output: 1 10 30 20 ie the two ways of accessing the members of shown below. In the above program, noti a one way is using the object and dot operator as ‘ e.add( 6, 5)7 , e.c = 10; % Here, ‘e’ is an object of class ‘simple’. The other way is using the arrow f Pointer to an object as shown below. { el-padd( 5, 25); el->e = 20; Here, ‘e1” is a pointer which is pointing to the object ‘e’ of class simple, using the arrow operator. ry / 2.11. THE ‘this’ POINTER ‘ fe i ‘is’ is a keyword which is used to store the address of the object that \* 1 oe member function, Each member function when invoked, a pointer implicitly i address of the object itself, and itis called the %bis’ pointer. There is no need to declare the ‘this’ pointer. It is internally defined, When an object is used to | class member function, then, the address of that object is automatically as | } ‘this’ pointer. Explicitly using the ‘this’ pointer: ‘We can explicitly use the ‘this’ pointer in a function definition as following example program 2.10, Program 2.10 /* 2,10.cpp*/ t ¥include
using namespace std;seas na onjecee = rmromeeon |) ass simple int az public: void set_data( int x) ( this->a = x; } void display (void) { cout << “The value of a = “ << this->a << endl; cout << “The address of object e = ° << this << endl; 5 int main( ) { simple e; e.set_data( 5); e.display( ); return 0; } Output: The value of a = 5 The address of object e = Ox8feerfe4 In the above program, we can observe that, to assign a value to the data member ‘a’, we do it through this->a = x; Because, ‘this’ is an inbuilt pointer which always points ot contains the address of the object with which the member functions is invoked. As soon as the member function is invoked, the address of the object with which it is invoked gets stored in the ‘this? pointer, Implicitly using the ‘this? pointer : Note that, in the below program, we are accessing the class member ‘a’ without using the ‘this’ pointer, : Program 2.11 /* 2.11.cpp*/ finclude
using namespace std;Class simple ‘ int a; Public: Void set_data( int x) { ae ) void display(void) ae << endl; : cout << “The value of a=" <
You might also like
Structures in C++
PDF
No ratings yet
Structures in C++
9 pages
Week 14
PDF
No ratings yet
Week 14
13 pages
Structure
PDF
No ratings yet
Structure
24 pages
C-Programming-Class 5
PDF
100% (1)
C-Programming-Class 5
44 pages
Basics: Structures - Struct
PDF
No ratings yet
Basics: Structures - Struct
30 pages
Structures Part 2
PDF
No ratings yet
Structures Part 2
16 pages
Chapter 2. Structure, Unions, and Enumerations
PDF
No ratings yet
Chapter 2. Structure, Unions, and Enumerations
41 pages
Structures
PDF
No ratings yet
Structures
16 pages
OOP Lab 1
PDF
No ratings yet
OOP Lab 1
8 pages
Unit 7 (C++) - Structures
PDF
No ratings yet
Unit 7 (C++) - Structures
44 pages
Structures and Enumeration-1
PDF
No ratings yet
Structures and Enumeration-1
10 pages
Structures in C
PDF
100% (2)
Structures in C
25 pages
BX4002 Unit 5
PDF
No ratings yet
BX4002 Unit 5
48 pages
Lab 08: Structures: National University of Technology
PDF
No ratings yet
Lab 08: Structures: National University of Technology
6 pages
Oop Lab 1
PDF
No ratings yet
Oop Lab 1
8 pages
Unit 8
PDF
No ratings yet
Unit 8
23 pages
Class and Structure: Instructor DR Farzana Rahman
PDF
No ratings yet
Class and Structure: Instructor DR Farzana Rahman
30 pages
Unit - 5 - GVK
PDF
No ratings yet
Unit - 5 - GVK
61 pages
Chapter 4 Structure Edited
PDF
No ratings yet
Chapter 4 Structure Edited
9 pages
Programming - U3 (Custom Data Type)
PDF
No ratings yet
Programming - U3 (Custom Data Type)
38 pages
Module 5
PDF
No ratings yet
Module 5
73 pages
Structures Programming
PDF
No ratings yet
Structures Programming
21 pages
ch8C++ Struction
PDF
No ratings yet
ch8C++ Struction
15 pages
PPS Unit-5-Structures
PDF
No ratings yet
PPS Unit-5-Structures
5 pages
Handouts For Lab 8
PDF
No ratings yet
Handouts For Lab 8
18 pages
Struct
PDF
No ratings yet
Struct
15 pages
Class and Objects:: Unit - 2
PDF
No ratings yet
Class and Objects:: Unit - 2
35 pages
DS Lecture 05.1 05.2
PDF
No ratings yet
DS Lecture 05.1 05.2
14 pages
Structures in C Programming
PDF
No ratings yet
Structures in C Programming
22 pages
Oop Lab 1
PDF
No ratings yet
Oop Lab 1
10 pages
Structure
PDF
No ratings yet
Structure
31 pages
Lecture 4 Structures in C++
PDF
No ratings yet
Lecture 4 Structures in C++
31 pages
Structures
PDF
No ratings yet
Structures
9 pages
2 Structures
PDF
No ratings yet
2 Structures
36 pages
1
PDF
No ratings yet
1
13 pages
Session 1 Recursive Function Pointer Structure and Self-Referential Structure - Manual
PDF
No ratings yet
Session 1 Recursive Function Pointer Structure and Self-Referential Structure - Manual
7 pages
WINSEM2023-24 BCSE102L TH VL2023240501147 2024-02-09 Reference-Material-I
PDF
No ratings yet
WINSEM2023-24 BCSE102L TH VL2023240501147 2024-02-09 Reference-Material-I
55 pages
Defining A Structure: Structs
PDF
No ratings yet
Defining A Structure: Structs
4 pages
Module 5
PDF
No ratings yet
Module 5
75 pages
Main PDF Lesson 4
PDF
No ratings yet
Main PDF Lesson 4
26 pages
Chapter-6 Pointers
PDF
No ratings yet
Chapter-6 Pointers
25 pages
Lecture 4
PDF
No ratings yet
Lecture 4
56 pages
Mit Opencourseware: 6.096 Introduction To C++
PDF
No ratings yet
Mit Opencourseware: 6.096 Introduction To C++
8 pages
Struct Assignment in C
PDF
100% (2)
Struct Assignment in C
4 pages
Structure
PDF
No ratings yet
Structure
29 pages
CModule IV
PDF
No ratings yet
CModule IV
16 pages
4-Structures e
PDF
No ratings yet
4-Structures e
36 pages
Unit 2 C Programming and Data Structures-1
PDF
No ratings yet
Unit 2 C Programming and Data Structures-1
53 pages
Module 05
PDF
No ratings yet
Module 05
20 pages
C++ Notes8
PDF
No ratings yet
C++ Notes8
6 pages
Unit 5
PDF
No ratings yet
Unit 5
26 pages
Structures: National University of Computer & Emerging Sciences
PDF
No ratings yet
Structures: National University of Computer & Emerging Sciences
35 pages
Unit 2
PDF
No ratings yet
Unit 2
51 pages
CSC 202 Session 3
PDF
No ratings yet
CSC 202 Session 3
14 pages
Lec # 1 (Introduction)
PDF
No ratings yet
Lec # 1 (Introduction)
47 pages
Structures Functions
PDF
No ratings yet
Structures Functions
13 pages
Lecture 2 2024-Structured Data and Pointers
PDF
No ratings yet
Lecture 2 2024-Structured Data and Pointers
67 pages
Lecture 4-7-1
PDF
No ratings yet
Lecture 4-7-1
73 pages