Download presentation
Presentation is loading. Please wait.
Published byRatna Iskandar Modified over 6 years ago
2
PREVIOUS KNOWLEDGE Through the last chapters – the pupil,
has the idea about Object Oriented Programming. are familiarized with the concept of classes and objects are capable of defining functions and structured data types. are aware of the need of function prototyping , the role of arguments in function calling , the different methods of passing values to the called functions and way of returning values to the calling function.
3
The pupil, acquires knowledge of the user defined data type - class and objects as the variables declared using such data type. (2) understands the concept of classes and objects. (3) develops the ability to identify the characteristics and behaviour of various classes. (4) defines C++ classes for solving problems. (5) develops skill in programming. (6) develops interest in studying more about real world objects.
4
A Structure can contain variables of different types or of the same type. The members inside a structure are easily accessible with out any restriction. One of the major characteristics of OOP is data hiding. C++ being an Object Oriented language, offers an important data type called - class to achieve the data hiding property. NOTE : A class is a way to bind data and functions together. But a structure provides a way to group data elements.
5
Eg: struct item { int itemno; float price; }; Eg: class item {
private: int itemno; float price; public : void getdata(); void putdata(); };
6
NEED FO R A CLASS :- If we want to represent - the details of students like: name , roll number, marks and Operations like : finding percentage, finding grade etc. , we need class to represent real world objects that have data type properties and associated operations. Classes are needed to represent real world entities, that not only have data type properties (their characteristics) but also associated operations (their behavior)
7
CLASSES :- A class is a user defined data type that binds data describing an entity and its associated function together under a single unit. It has members which consist of the – Data members , Constructor function, Destructor functions and Member functions. The structure and behavior of similar objects are defined in their common class. A class is a collection of Objects . The objects belonging to a class are called instances of the class.
8
DECLARATION OF A CLASS :-
CLASS SPECIFICATION:- A class specification does not define any object of its type, rather it just defines the properties of a class. A class specification has two parts: Class declaration – It describes the component members ( both data members and function members ) of the class. Class method definition ( member function definition ) – It describes how certain class member functions are implemented. DECLARATION OF A CLASS :- The general form of a class definition – class class_name { Access label1: Variable declarations; Function declarations; Access label2: Access label3: }; The keyword class is used to declare a class.
9
Declaration of classes involves declaration of its 4 associated attributes
Data members : They are the variables that are declared in a class. They describe the characteristics of a class. Member functions : They are the operations performed on data members of a class. Program Access levels : control access to members from within the program. These access levels are : private, protected or public. Class_name (tagname) : serves as a type specifier for the class using which objects of this class type will be created.
10
VISIBILITY OF CLASS MEMBERS : -
Private members can be accessed only from within the class. They are hidden from the outside world. These members implement the OOP concept of data hiding. They can be used only by member functions and friends of the class in which it is declared. ( A friend of a class is a function that is not a member of the class but is permitted to use the private and protected members from the class.) Public members can be accessed from anywhere outside the class where the class is visible. They can be directly accessed by any function i.e member function of the class or non-member functions. Hence the keyword public provides the class members the public interface. Protected members are similar to private members but differ in the context of inheritance. If we declare the members of a class without specifying the access label the members are by default private.
11
Eg : class student { int rollno; // private by default float marks; public : void getdata(); void display(); }; We can also declare a class without member functions and data members . Such a class is called an empty class.
12
EVALUATION :- Question. How a class in C++ supports some major OOP concepts : Data hiding, Abstraction and Encapsulation? Ans. Private and protected members remain hidden from outside world and thereby support Data hiding. Since the class members (data & functions) which are private and protected remains hidden from outside world, the public members form the interface by providing the essential and relevant information to outside world . Thus only the essential features (public members) are represented to outside world without including the background details (private and protected members) – which is Abstraction. Class binds the data and associated functions together into a single type which is Encapsulation.
13
(i) Outside the class definition:-
THE CLASS METHOD DEFINITION:-providing code for the member functions. Member functions can be defined in two places : Outside the class definition Inside the class definition. (i) Outside the class definition:- The member function definition outside the class definition is much the same as that of function definitions , with only difference : the name of the function is the full name ( qualified name) of the function i.e returntype class_name :: function_name (Parameter list) { function body; } Where , class_name – indicates that the function specified by function _name is a member of the class specified by class_name :: - called scope resolution operator, specifies that the scope of the function is restricted to the class class_name.
14
(ii) Inside the class definition:- When a member function is defined inside a class, the function definition is just similar to the function definitions (i.e) no need to put membership label along with the function name. Only small functions are usually defined inside the class definition. A function defined inside a class is an inline function Inline property is a hint to the compiler to insert the code for the body of the function ( declared inline) at the place where it is called, there by saving the overheads (i.e) time spent in loading and unloading of the called function) of a function call.
15
{ cout<<“\n Roll No. “<<rollno;
Example for inside class definition class student { int rollno; // private by default float marks; public : void getdata() { cout<<“\n Enter roll number : “; cin>>rollno; cout<<“\n Enter marks : “; cin>>marks; } void display() cout<<“\n Roll No. “<<rollno; cout<<“\n marks : “<<marks; }; Example for outside class definition class student { int rollno; // private by default float marks; public : void getdata(); void display(); }; void student::getdata() { cout<<“\n Enter roll number : “; cin>>rollno; cout<<“\n Enter marks : “; cin>>marks; } void student::display() { cout<<“\n Roll No. “<<rollno; cout<<“\n marks : “<<marks;
16
EVALUATION :- Question. What are the differences between a data type struct and data type class in C++? Ans. For the Data type Class - the struct keyword has been substituted by the keyword class It also declares member functions along with the data members It divides its members into segments : public , private and protected By default all members are public in a structure but private in a class.
17
Declaration of a class does not allocate any memory for storing data
Declaration of a class does not allocate any memory for storing data. Objects have to be declared for memory allocation. When an object is declared memory is allocated for storing of all data members. The declaration of an object is similar to that of a variable of any basic type. The syntax of defining the object is : Class_name object_name; Eg: student A1, A2, A3 ; Will create 3 objects A1, A2 and A3 of student class type.
18
Using Objects : When we define a class, it does not create objects of that class, rather it only specifies what type of information the objects of this class type will be containing. Once a class has been defined , its objects ( the variables of this class type, its instances ) can be created (like any other variable ), using the class name as type specifier. (i.e) class_name objectlist(comma separated); Eg: class item { private: int itemno; float price; public : void getdata(int i, float j) { itemno = i; price = j; } void putdata() { cout<<“Items ”<<itemno; cout<<“\nPrice”<<price; } }; item S1, S2; void main() S1.getdata(1001, 17.50); S2.getdata(1002, 29.50); …..
19
In the function main( ). The statements: S1.getdata(1001,17.50);
invokes the member function getdata( )for objects S1 and S2 respectively with data 1001 & for s1 and 1002 & for s2. After these statements, the getdata( ) function (for S1&S2) stores given values in the object S1&S2. NOTE:- Memory space for objects is allocated when they are declared and not when the class is defined. When we call a member function , it uses the data members of the particular object used to invoke the member function. Member functions are created and stored in the memory space only once when the class is defined and this memory space (containing member functions) can be read by any of the objects of that class. The memory space is allocated for objects, data members only when the objects are declared because the data members hold different values for different objects. No separate space is allocated for member functions when the objects are created.[ since all the objects belonging to a class use the same member functions, there is no point allocating separate space for member functions for each object.
20
REFERENCING CLASS MEMBERS:-
The members of a class are referenced using object of the class The private data of a class can be accessed only through the member functions of that class. The public data member can be accessed by the non-member functions through the objects of that class using the format : Object_name.publicdatamember Eg: A1.Z ( if Z is a public data member) (if Z is a private data member then the compiler will report an error.) The public member functions of a class are called by non – member functions using the objects. The general format for calling a public member function is : Object_name . publicfunction_name(actual_Arguments); Eg: A1.getdata(): A1.getdata(2,3);
21
1. Define a class worker with the following specifications:-
private members of the class worker: wno integer wname 25 characters hrwrk,wgrate float(hour worked and wage rate per hour) Totwage float(hrwrk*wgrate) calwg() A function to find hrwrk * wgrate with float return type public members of the class worker: in_data() function to accept values for wno,wname, hrwrk,wgrate and invoke calcwg() to calculate total pay. out_data() function to display all the data members on the screen. You should give definitions of functions.
22
float hrwrk,wgrate,totwage; float calcwg() return(hrwrk*wgrate) }
Ans. class worker { int wno; char wname[25]; float hrwrk,wgrate,totwage; float calcwg() return(hrwrk*wgrate) } void worker::in_data() { cout<<”\n Enter Worker number”; cin>> wno; cout<< “\nEnter worker name:” cin>> wname; cout<<”\n Enter hours worked”; cin>> hrwrk; cout<< “\nEnter wage rate per hour:” cin>> wgrate; totwage=calcwg(); } public : void in_data(); void out_data(); }; void worker::out_data() { cout<<”\nworker Number :”<<wno; cout<<”\nworker Name :”<<wname; cout<<”\nHours worked :”<<hrwrk; cout<<”\nwage rate per hour :”<<wgrate; cout<<”\nTotal wage:”<<totwage; }
23
2. Define a class student with the following specifications:-
private members of the class student: admno integer sname 20 characters English,math,science float Total float Ctotal() A function to calculate English+math+science with float return type public members of the class student: Takedata() function to accept values for admno, sname, English,math,science and invoke ctotal() to calculate total. Show data() function to display all the data members on the screen. Ans. class student {int admno; char sname[20]; float English,math,science; float total; float ctotal() { return(English+math+science); }
24
public : void takedata() { cout<<”\n Enter admission number”; cin>> admno; cout<< “\nEnter name:” cin>> sname; cout<<”\n Enter English Marks”; cin>> English; cout<< “\nEnter Maths marks:” cin>> math; cout<< “\nEnter science marks:” cin>> science; total=ctotal(); } void showdata() { cout<<”\nAdmission number :”<<admno; cout<<”\nName :”<<sname; cout<<”\nEnglish marks:”<<English; cout<<”\nMaths marks:”<<math; cout<<”\nScience marks:”<<science; cout<<”\nTotal marks:”<<total; } };
25
ARRAYS WITH IN A CLASS:-
A class can have an array as its member variable. An array in a class can be private or public data member of the class. [If an array happens to be a private data member of the class , then only the member functions of the class can access it. If an array is a public data member of the class, it can be accessed directly using objects of this class type.] When a member function is called by another member function of the same class , it is known as nesting of member functions.
26
ARRAY OF OBJECTS:- An array having class type elements is known as array objects. An array of objects is declared after the class definition is over and it is defined in the same way as any other type of array is defined. Syntax : class_name object_name[size]; Eg: Item order[10]; - array order contains 10 objects of item type Order[0] To access data member itemno of 3rd object in the arry use : Order[2].itemo Similarly to make putdata( ) for 7th object in the array use: Order[6].putdata( ); Order[1] Order[2] Order[9]
27
Element Scope Description SCOPE RULES OF CLASSES : Class Global
Global Scope This class type is globally available to all the functions within a program. Therefore , the objects of this class type can be created from any function within the program. Local Local Scope This class type is locally available to all the function in which the class definition occurs. The objects of this class type can be created only within the function that defines this class type. object Global Global Scope This object can be used anywhere in the program by any function Local Local Scope This object can be used only within the function that declares it. Class Members private Class scope These members can be accessed only by the member functions of the class. These cannot be accessed directly by using objects public Global for global objects Local for local objects The scope of public members depends upon the referencing object. If the referencing object is local, the scope of public member is local. If the referencing object is global, the scope of public member is global.
28
Member functions of a class can be categorize into followig three categories:
Accessor functions: These are the member functions that allow us to access the data members (field) of object. Accessor functions cannot /do not change the value of data members Accessor methods are used to read values of private data members of a class which are directly not accessible in non-member function. If we provide a public accessor function for that, the value of private data members becomes accessible yet being safe as accessor functions do not modify data.[If a user wants to know the current value of a private data member , get it through an accessor function. Mutator functions: These are member functions that allow us to change the data members of an object. Manager functions : These are member functions with specific functions i.e constructors and destructors that deal with initializing and destroying class instances. Accessors and Mutators are sometimes called getters and setters. By making everything public, data becomes unsafe and vulnerable defeating the very purpose of object orientation. Hence we use Acccessors and mutators.
29
Eg:- class student { int rollno; // private by default float marks; public : void getdata(); void display(); int getroll() // Accessor method { return rollno; } void calcgrade()// Mutator method { if marks >=75 grade =‘A’; else if marks >=60 grade =‘B’; else if marks >=50 grade =‘C’; else grade =‘F’; }; void student::getdata() { cout<<“\n Enter roll number: “; cin>>rollno; cout<<“\n Enter marks : “; cin>>marks; } void student::display() { cout<<“\n Roll No. “<<rollno; cout<<“\n marks : “<<marks;
30
Functions in a class :- Inline functions :- Inline function definition should be placed above all the functions that call it. Advantages:- The inline functions are designed to speed up programs. Inline functions run a little faster than the normal functions as function calling – overheads are saved. Drawback: There is a memory penalty [ i.e if 10 times an inline function is called, there will be 10 copies of the function inserted into the code] Difference between the normal functions and inline functions: The coding of normal functions and inline functions is similar except that inline functions definitions start with the keyword inline. Difference is in compilation process. Eg: - inline void maxi(int a, int b) { cout<<(a>b:a:b); } void main( ) { int x, y; cin >> x >> y; maxi( x, y ); …… }
31
OVERHEADS INVOLVED IN CALLING A FUNCTION:-
After writing the program, it is first compiled to get an executable code, which consists of a set of machine language instructions. When this executable code is executed, the operating system loads these instructions into the computer memory, so that each instruction is stored in a specific memory location. After loading the executable program in the computer memory, these instructions are executed step by step. Steps in executing a function : Save the address of instruction immediately following the function call, and loads the function being called into the memory. Copy argument values in Stack.( a memory area) Jump to the memory location of the called function Execute the instructions in the function Store the returned value (of the function) Jump back to earlier saved address of instructions that was saved just before executing the called function.
32
With inline functions , the compiler does not have to jump to another location to execute the function, and then jump back as the code of the called function is already available to the calling program. Points to note for making a function inline :- A function can be inline if – it is very small. it is not recursive it does not contain static variables it does not contain any loop it does not contain return statement. The inlining does not work for following situations : For functions that return values and are having a loop or a switch or a goto for functions not returning values , if a return statement exists If functions contain static variable(s) (4) If the function is recursive.
33
Member function of a class, if defined with in the class definition are inlined by default (Only small functions should be defined with in the class definition) Member functions defined outside the class definition can be made explicitly inline by placing the keyword inline before their definition.
34
CONSTANT MEMBER FUNCTIONS:
If a member function of a class does not alter any data in the class, then, this member function may be declared as a constant member function using the keyword const Eg: int maxi( int , int ) const; void prn( ) const; NOTE:- The qualifier const appears both in member function declarations and definitions. Once a member function declared as const, it cannot alter the data values of the class. The compiler will generate an error message if such functions try to alter the data values.
35
SCOPE RESOLUTION OPERATOR(::) :-
:: - is used to distinguish between class member names and other names. Eg: int X, Y; class A { int X; float Y; public : void readm( ) const; ………. }; (2) If a class defines a member with the same name as that of a global variable, then the global variable becomes hidden. To access the global varible, use the scope resolution operator :: before the global variable name. Eg: A::X refers to X of Class A And :: X refers to the global variable. In this class – The full name ( qulified name ) of variable X is A::X. Similarly , the qualified name of y is A::Y The qualified name of readm() is a::readm() To define a member function outside a class , the scope resolution operator is used.
36
File scope items (Global items in a file) are normally hidden when we use the same name for an item with in a block ( class block, function block, or any other block) , but we can uncover them with the :: operator.
37
OBJECTS AS FUNCTION ARGUMENTS:-
An object may also be passed to a function as an argument. An object can be passed both ways. By value: - When an object is passed by value, the function creates its own copy of the object and works with its own copy. Therefore any changes made to the object inside the function do not affect the original object. By Reference :- When an object is passed by reference, its memory address is passed to the function so that the called function works directly on the original object used I the function call. Thus any changes made to the object inside the function are reflected in the original object as the function is making changes in the original object itself.
38
FUNCTIONS RETURNING OBJECTS:-
Objects can not only be passed to functions but functions can also return an object. Ans. class distance {int feet,inches; public : void getdata(int f,int i) {feet=f; inches=I; } void printit() { cout<<feet<<“feet”<<inches<<“inches”<<“\n”; Distance sum(distance d2); }; Distance Distance::sum(Distance d2) { Distance d3; D3.feet=feet+d2.feet+(inches +d2.inches)/12; D3.inches=(inches+d2.inche s)%12; return(d3); }
39
void main() { Distance length1,length2,total; length1.getdata(17,6); length2.getdata(13,8); total=length1.sum(length2); cout<<“length1:”; length1.printit(); cout<<“length2:”; length2.printit(); cout<<“Total Length:”; total.printit(); }
40
STATIC CLASS MEMBERS:-
There may be static data members and static member functions in a class. STATIC DATA MEMBER: It is like a global varible for its class (i.e) it is globally available for all the objects of that class type. It is usually maintained to store values common to the entire class.[ It is used to keep track of its number of existing objects. Difference between static data member and ordinary data members of a class : - There is only one copy of this data member maintained for the entire class which is shared by all the objects of that class. It is visible only within the class, its lifetime ( the time for which it remains in the memory ) is the entire program.
41
FOR MAKING A DATA MEMBER STATIC:-
Declaration within the class definition :- declaration of a static data member within the class definition is similar to any other varible declaration except that it starts with the keyword static. Eg: class x { static int count; ….. }; 2. Definition outside the class definition : - The definition of above declared static member count outside the classs will be : int X :: count; A static data member can be given an initial value at time of its definition . Eg: int X::count =10;
42
[ static member is not a part of object of a class ]
REMEMBER:- 1. A Static data member must be defined outside the class definition as these are stored separately rather than as a part of an object [ static member is not a part of object of a class ] 2. Since a static data member are associated with the class itself rather than with any object, they are alos known as class variables. We cannot have a static data member inside a local class i.e in a class that has benn defined inside a function. Object 2 Object 1 Object 3 Static member being shared by all objects
43
STATIC MEMBER FUNCTION:-
A member function that accesses only the static members of a class is declared as static by using keyword static before the function declaration in the class definition Eg: class X { static int count; static void show() { cout<< count<<“\n”; } }; int X::count ; A static member functions can use only the names of static members and enumerators.
44
Exercise Programs Contd…
DIFFERENCE BETWEEN STATIC MEMBER FUNCTIONS AND OTHER MEMBER FUNCTIONS:- A static member function can access only static members ( functions or variables ) of the same class. A static member function is invoked by uisng the class name instead of its objects as per the syntax : Class_name :: function_name Eg: X::Show(); Exercise Programs Contd… in the study material
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.