classes & objects in cpp

41
Classes & Objects Chap 5 06/19/2022 1 By:-Gourav Kottawar

Upload: gourav-kottawar

Post on 13-Jan-2017

184 views

Category:

Education


0 download

TRANSCRIPT

Page 1: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 1

Classes & Objects Chap 5

Page 2: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 2

Contents5.1 A Sample C++ Program with class 5.2 Access specifies 5.3 Defining Member Functions 5.4 Making an Outside Function Inline

5.5 Nesting of Member Functions5.6 Private Member Functions 5.7 Arrays within a Class 5.8 Memory Allocation for Objects 5.9 Static Data Members, Static Member 5.10 Functions, Arrays of Objects5.11 Object as Function Arguments

5.12 Friend Functions, Returning Objects, 5.13 Const member functions 5.14 Pointer to Members, Local Classes 5.15 Object composition & delegation

Page 3: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 3

Declaring Class Syntax –class class_name{

private :variable declaration;function declaration;

public:variable declaration;function declaration;

}

Page 4: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 4

Data hiding in classes

Page 5: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 5

Simple class programCreating objectsAccessing class membersAccess specifies

privatepublicprotectordefault - private

5.3 Defining Member Functions

Page 6: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 6

5.4 Making an Outside Function Inline

class item{............public:void getdata(int a,float b);};inline void item :: getdata(int a,float b){number=a;cost=b;}

Page 7: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 7

5.5 Nesting of Member Functions#include<iostream.h> #include<conio.h> class data {

int rollno,maths,science; int avg();

public: void getdata(); void putdata();

}; main() { clrscr(); data stud[5]; for(int i=0;i<5;i++) stud[i].getdata(); }

void data::getdata() { cout<<"Please enter rollno:"; cin>>rollno; cout<<"Please enter maths marks:"; cin>>maths; cout<<"Please enter science marks:"; cin>>science; putdata(); } int data::avg() { int a; a=(maths+science)/2; return a; } void data::putdata() { cout<<"Average is :"<<avg()<<endl; }

Page 8: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 8

5.7 Arrays within a Class

const int size=10;

class array{int a[size];public:void setval(void);void display(void);};

Page 9: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 9

Ex-#include<iostream>#include<string>using namespace std;

const int  val=50;

class ITEM{private:    int item_code[val];    int item_price[val];    int count;public:    void initiliaze();    void get_item();    void display_item();    void display_sum();    void remove();};

void ITEM::initiliaze(){    count=0;}

void ITEM::get_item(){    cout<<"Enter the Item code == "<<endl;    cin>>item_code[count];

    cout<<"Enter the Item cost == "<<endl;    cin>>item_price[count];    count++;}void ITEM::display_sum(){    int sum=0;    for(int i=0; i<count;i++)    {        sum=sum + item_price[i];    }    cout<<"The Total Value Of The Cost Is == "<<sum<<endl;}

Page 10: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 10

void ITEM::display_item(){    cout<<"\nCode  Price\n";    for(int k=0;k<count;k++)    {        cout<<"\n"<<item_code[k];        cout<<"   "<<item_price[k];    }}void ITEM::remove(){    int del;    cout<<"Enter the code you want to remove == ";    cin>>del;    for(int search=0; search<count; search++)    {        if(del == item_code[search])        {            item_price[search]=0;            item_code[search]=0;        }    }}

Page 11: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 11

int main(){    ITEM order;

    order.initiliaze();    int x;    do    {        cout<<"\n\nYou have the following opton";        cout<<"\nEnter the Appropriate number";

        cout<<"\n\nPress 1 for ADD AN ITEMS";        cout<<"\n\nPress 2 for DISPLAY TOTAL VALUE";        cout<<"\n\nPress 3 for DELETE AN ITEM";        cout<<"\n\nPress 4 for DISPLAY ALL ITEMS";        cout<<"\n\nPress 5 for QUIT";

        cout<<"\nEnter The Desired Number == \n";        cin>>x;   

    switch(x)        {        case 1:            {                order.get_item();                break;            }        case 2:            {                order.display_sum();                break;            }        case 3:            {                order.remove();                break;            }        case 4:            {                order.display_item();                break;            }      

Page 12: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 12

  case 5:            break;        default: cout<<"Incorrect option Please Press the right number == ";        }

    }while(x!=5);

    getchar();    return 0;}

Page 13: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 13

5.8 Memory Allocation for Objects

common for all objects member function 1

member function 2 memory created when

function defined

Object 1 object 2 object 3Member varible 1 member variable 2 member

variable 1

Member variable 2 member variable 2 member variable 2

memory created

when objects defined

Page 14: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 14

5.9 Static Data Members, Static Member

A data member of a class can be qualified as static.

The properties of a static member variable are similar to that of a C static variable.

It is initialized to zero when the first object of its class is created. No other initialization is permitted.

Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.

It is visible only within the class, but its lifetime is the entire program.

Page 15: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 15

#include using namespace std;

class item{static int count;int number;public:void getdata(int a){number = a;count ++;}void getcount(void){cout << "Count: ";cout << count <<"\n";}};int item :: count;

int main(){item a,b,c;a.getcount();b.getcount();c.getcount();

a.getdata(100);b.getdata(200);c.getdata(300);

cout << "After reading data"<<"\n";a.getcount();b.getcount();c.getcount();return 0;}

Page 16: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 16

#include using namespace std;

class item{static int count;int number;public:void getdata(int a){number = a;count ++;}void getcount(void){cout << "Count: ";cout << count <<"\n";}};int item :: count;

int main(){item a,b,c;a.getcount();b.getcount();c.getcount();

a.getdata(100);b.getdata(200);c.getdata(300);

cout << "After reading data"<<"\n";a.getcount();b.getcount();c.getcount();return 0;}

The output of the program would be:Count: 0Count: 0Count: 0After reading dataCount: 3Count: 3Count: 3

Page 17: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 17

Sharing of a static data member

Page 18: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 18

Static member functionA member function that is

declared static has following properties

1. A static function can have access to only other static members (functions or variables) declared in the same class.

2. A static member function can be called using the class name (instead of its objects ) as follows :class – name :: function – name;

Page 19: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 19

class Something{private:    static int s_nValue;public:    static int GetValue() { return s_nValue; }}; int Something::s_nValue = 1; // initializer int main(){    std::cout << Something::GetValue() << std::endl;}

Page 20: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 20

class IDGenerator{private:    static int s_nNextID; public:     static int GetNextID() { return s_nNextID++; }}; // We'll start generating IDs at 1int IDGenerator::s_nNextID = 1; int main(){    for (int i=0; i < 5; i++)        cout << "The next ID is: " << IDGenerator::GetNextID() << endl;     return 0;}

The next ID is: 1 The next ID is: 2 The next ID is: 3 The next ID is: 4 The next ID is: 5

Page 21: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 21

class IDGenerator{private:    static int s_nNextID; public:     static int GetNextID() { return s_nNextID++; }}; // We'll start generating IDs at 1int IDGenerator::s_nNextID = 1; int main(){    for (int i=0; i < 5; i++)        cout << "The next ID is: " << IDGenerator::GetNextID() << endl;     return 0;}

Page 22: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 22

Array of object

Page 23: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 23

5.11 Object as Function Arguments

Two ways1. A copy of the entire object is

passed to the function.i.e. pass by value

2. Only the address of the object is transferred to the functioni.e. pass by reference

Page 24: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 24

Page 25: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 25

#include <iostream> using namespace std; class Complex {

private: int real; int imag; public:

void Read() { cout<<"Enter real and imaginary number

respectively:"<<endl; cin>>real>>imag; } void Add(Complex comp1,Complex comp2) {

real=comp1.real+comp2.real;

/* Here, real represents the real data of object c3 because this function is called using code c3.add(c1,c2); */

imag=comp1.imag+comp2.imag;

/* Here, imag represents the imag data of object c3 because this function is called using code c3.add(c1,c2); */ }

Page 26: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 26

void Display() {

cout<<"Sum="<<real<<"+"<<imag<<"i"; } }; int main() { Complex c1,c2,c3; c1.Read(); c2.Read(); c3.Add(c1,c2); c3.Display(); return 0; }

Page 27: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 27

Returning Object from Function

Page 28: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 28

#include <iostream> using namespace std; class Complex { private: int real; int imag; public: void Read() {

cout<<"Enter real and imaginary number respectively:"<<endl; cin>>real>>imag; } Complex Add(Complex comp2) {

Complex temp; temp.real=real+comp2.real;

/* Here, real represents the real data of object c1 because this function is called using code c1.Add(c2) */

temp.imag=imag+comp2.imag; /* Here, imag represents the imag data of object c1 because this function is called using code c1.Add(c2) */

return temp; 0; }

Page 29: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 29

} void Display() { cout<<"Sum="<<real<<"+"<<imag<<"i"; } };

int main() { Complex c1,c2,c3; c1.Read(); c2.Read(); c3=c1.Add(c2); c3.Display(); return 0;}

Page 30: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 30

5.12 Friend function Need a data is declared as private inside a class,

then it is not accessible from outside the class.

A function that is not a member or an external class will not be able to access the private data.

A programmer may have a situation where he or she would need to access private data from non-member functions and external classes. For handling such cases, the concept of Friend functions is a useful tool.

Page 31: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 31

5.12 Friend functionWhat is a Friend Function? A friend function is used for

accessing the non-public members of a class.

A class can allow non-member functions and other classes to access its own private data, by making them friends.

Thus, a friend function is an ordinary function or a member of another class.

Page 32: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 32

5.12 Friend functionGeneral syntaxClass ABC{

…..…..public :…..…..

Friend void func1(void);};

Page 33: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 33

5.12 Friend functionSpecial Characteristics The keyword friend is placed only in the function declaration

of the friend function and not in the function definition. It is not in the scope of the class to which it has been declared

as friend. It is possible to declare a function as friend in any number of

classes. When a class is declared as a friend, the friend class has

access to the private data of the class that made this a friend. A friend function, even though it is not a member function,

would have the rights to access the private members of the class.

It is possible to declare the friend function as either private or public without affecting meaning.

The function can be invoked without the use of an object. It has object as argument.

Page 34: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 34

#include <iostream>using namespace std; 

class exforsys{private:        int a,b;public:        void test()        {                a=100;                b=200;        }        friend int compute(exforsys e1);                //Friend Function Declaration with keyword friend and with the object of class exforsys to which it is friend passed to it};int compute(exforsys e1){        //Friend Function Definition which has access to private data

        return int(e1.a+e1.b)-5;}void main(){       exforsys e;        e.test();        cout << "The result is:" << compute(e);                //Calling of Friend Function with object as argument.

}

Page 35: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 35

Constant Member Functions

Declaring a member function with the const keyword specifies that the function is a "read-only" function that does not modify the object for which it is called.

A constantmember function cannot modify any non-static data members or call any member functions that aren't constant.

The const keyword is required in both the declaration and the definition.

Page 36: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 36

Constant Member Functions – EX class Date { public:

Date( int mn, int dy, int yr ); int getMonth() const; // A read-only function void setMonth( int mn ); // A write function; can't be const private: int month;

}; int Date::getMonth() const {

return month; // Doesn't modify anything

}

void Date::setMonth( int mn ) { month = mn; // Modifies data member }

int main() { Date MyDate( 7, 4, 1998 ); const Date BirthDate( 1, 18, 1953 ); MyDate.setMonth( 4 ); // Okay BirthDate.getMonth(); // Okay BirthDate.setMonth( 4 ); // C2662 Error }

Page 37: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 37

5.14 Pointers to members Pointers to members allow you to refer to nonstatic

members of class objects. You cannot use a pointer to member to point to a

static class member because the address of a static member is not associated with any particular object.

To point to a static class member, you must use a normal pointer.

You can use pointers to member functions in the same manner as pointers to functions.

You can compare pointers to member functions, assign values to them, and use them to call member functions.

Note - a member function does not have the same type as a nonmember function that has the same number and type of arguments and the same return type.

Page 38: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 38

5.14 Pointers to members - Ex#include <iostream> using namespace std; class X {

public: int a; void f(int b) { cout << "The

value of b is "<< b << endl;

} };

int main() { // declare pointer to data member int X::*ptiptr = &X::a; // declare a pointer to member function void (X::* ptfptr) (int) = &X::f; // create an object of class type X X xobject; // initialize data member xobject.*ptiptr = 10; cout << "The value of a is " << xobject.*ptiptr << endl; // call member function (xobject.*ptfptr) (20); }

Page 39: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 39

5.14 Local ClassesA local class is declared within a function

definition. Declarations in a local class can only use type

names, enumerations, static variables from the enclosing scope, as well as external variables and functions.

Member functions of a local class have to be defined within their class definition, if they are defined at all.

As a result, member functions of a local class are inline functions. Like all member functions, those defined within the scope of a local class do not need the keyword inline.

Page 40: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 40

int x; // global variable void f() // function definition { static int y; // static variable y can be used by local class int x; // auto variable x cannot be used by local class extern int g(); // extern function g can be used by local class class local // local class {

int g() { return x; } // error, local variable x // cannot be used by g

int h() { return y; } // valid,static variable y int k() { return ::x; } // valid, global x int l() { return g(); } // valid, extern function g

}; } int main() { local* z; // error: the class local is not visible // ...}

Page 41: classes & objects in cpp

05/01/2023 By:-Gourav Kottawar 41

A local class cannot have static data members. void f() { class local { int f(); // error, local class has noninline

// member function int g() {return 0;} // valid, inline member function static int a; // error, static is not allowed for // local class int b; // valid, nonstatic variable }; } // . . .