1 / 47

Introduction To C++

Introduction To C++. Prepared by N. Sathish Kumar CSE/Lecturer SKREC URL Source: www.nskinfo.com Room No: A206. Classes access specifiers function and data members default arguments function overloading friend functions const and volatile functions static members. Objects

josie
Download Presentation

Introduction To C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction To C++ Prepared by N. Sathish Kumar CSE/Lecturer SKREC URL Source: www.nskinfo.com Room No: A206

  2. Classes access specifiers function and data members default arguments function overloading friend functions const and volatile functions static members Objects pointers and objects constant objects nested classes local classes Introduction To C++CONTENTS

  3. Classes in C++ • A class definition begins with the keyword class. • The body of the class is contained within a set of braces, { } ; (notice the semi-colon). class class_name { …. …. …. }; Any valid identifier Class body (data member + methods)

  4. Classes in C++ • Within the body, the keywords private: and public: specify the access level of the members of the class. • the default is private. • Usually, the data members of a class are declared in the private: section of the class and the member functions are in public: section.

  5. Classes in C++ class class_name { private: … … … public: … … … }; private members or methods Public members or methods

  6. Inheritance • The mechanism by which one class can inherit the properties of another. • It allows a hierarchy of classes to be built, moving from the most general to the most specific.

  7. Base Class, Derived Class • Base Class • Defines all qualities common to any derived classes. • Derived Class • Inherits those general properties and adds new properties that are specific to that class.

  8. Example: Base Class class base { int x; public: void setx(int n) { x = n; } void showx() { cout << x << ‘\n’ } };

  9. Example: Derived Class // Inherit as public class derived : public base { int y; public: void sety(int n) { y = n; } void showy() { cout << y << ‘\n’;} };

  10. Example: main() int main() { derived ob; ob.setx(10); ob.sety(20); ob.showx(); ob.showy(); }

  11. An incorrect example class derived : public base { int y; public: void sety(int n) { y = n; } /* Error ! Cannot access x, which is private member of base. */ void show_sum() {cout << x+y; } };

  12. Access Specifier: private • If the access specifier is private: • public members of base become private members of derived. • these members are still accessible by member functions of derived.

  13. Example: Derived Class // Inherit as private class derived : private base { int y; public: void sety(int n) { y = n; } void showy() { cout << y << ‘\n’;} };

  14. Example: main() int main() { derived ob; ob.setx(10); // Error! setx() is private. ob.sety(20); // OK! ob.showx(); // Error! showx() is private. ob.showy(); // OK! }

  15. Protected Members • Sometimes you want to do the following: • keep a member of a base class private • allow a derived class access to it • Use protected members! • If no derived class, protected members is the same as private members.

  16. 3 Types of Access Specifiers • Type 2: inherit as protected

  17. 3 Types of Access Specifiers • Type 3: inherit as public

  18. Access specifiers Specify whether the data defined will be available to the users of the objects of the class. Public Private Protected Public: the data defined under public is available to objects. Private: data defined under private is not available to objects.

  19. Class student { Public : int RollNo; private: string name; string address; public: void PrintDetails() { cout <<rollno; cout <<name; cout << address; } }; void main() { student student1; student1.RollNo= 7; student1.name= “X”; // does not work since name is private student1.address= “Y”; // does not work since name is private Student1.PrintDetails(); }

  20. Function and data member Functions can be defined either inside or outside the class. Defining function members outside class very simple to define functions outside class If the functions are big—define outside Static data members of class Static members are stored at a location where they are retained throughout the execution of the program and are not stored with class objects. Stored only as a single copy– similar to member functions. All the static data members are initialized to zero at the time of declaration.

  21. Class student //defining function members outside class { Public : int RollNo; string name; string address; void PrintDetails(); //prototype }; void student :: PrintDetails() { cout <<rollno; cout <<name; cout << address; } }; void main() { student student1; student1.RollNo= 7; student1.name= “X”; student1.address= “Y”; Student1.PrintDetails(); }

  22. class student { public: static int PassingMark; int SubjectMark[5]; bool fail; void DisplayMarks() { for (int i=0;i<5;++i) { cout <<“Marks of subject No.”; cout <<i<<“is” <<SubjectMark[i]; } } void SetMarks (int Marks[5] { for (int i=0; i<5; ++i) { SubjectMarks[i]=Marks[i]; } } bool CheckPassing() { fail=false; for (int i=0;i<5; ++i) { if (SubjectMark[i]<PassingMark) fail= true; } if (fail) cout << “congratulations! You are passing\n”; else cout <<“sorry ! You are failing\n”; return !fail; }};

  23. int student:: PassingMark; //required definition void main() { student::PassingMark=35; student X; student Y; int Xmarks[]={75,55,65,56,89}; int Ymarks[]={15,25,100,98,89}; X.SetMarks(Xmarks); Y.SetMarks(Ymarks); X.CheckPassing(); Y.CheckPassing(); }

  24. Default Arguments A default argument is a value given in the function declaration that the compiler automatically inserts if the caller does not provide a value for that argument in the function call. Syntax: return_typef(…, type x = default_value,…);

  25. Default Arguments (Examples) The default value of the 2nd argument is 2. This means that if the programmer calls pow(x), the compiler will replace that call with pow(x,2), returning x2 doublepow(double x, int n=2) // computes and returns xn

  26. Default Arguments (Rules) Once an argument has a default value, all the arguments after it must have default values. Once an argument is defaulted in a function call, all the remaining arguments must be defaulted. intf(int x, int y=0, int n) // illegal intf(int x, int y=0, int n=1) // legal

  27. Function overloading Function redefined with different set of arguments. EX: add(float, float) Add(int, int) Add (int, int, int) Function overloading is useful when similar function is required to be called with either variable number of arguments or arguments of different type or both.

  28. Function Overloading Two or more functions can have the same name but different parameters Example: • int max(int a, int b) { • if (a>= b) • return a; • else • return b; • } • float max(float a, float b) { • if (a>= b) • return a; • else • return b; • }

  29. What 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. How to define and use Friend Function in C++: • The friend function is written as any other normal function, except the function declaration of these functions is preceded with the keyword friend. The friend function must have the class to which it is declared as friend passed to it in argument. Some important points • The keyword friend is placed only in the function declaration of the friend function and not in the function definition. 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. • It is possible to declare the friend function as either private or public. • The function can be invoked without the use of an object.

  30. Friend function class class1{private:int num;public:void get(){cout<<"Number:";cin>>num;}friend void display(class1 cl);};void display(class1 c1){cout<<C1.NUM;}int main(){class1 cls;cls.get();display(cls);}

  31. //static member friend function matrix multiplication #include<iostream.h> #include<conio.h> class matrixvector { static int a[3][3]; static int b[3]; static int c[3]; public: void getmatrix(void); void getvector(void); friend int multiply(matrixvector mv) }; int matrixvector::a[3][3]; int matrixvector::b[3]; int matrixvector::c[3]; void matrixvector::getmatrix(void) { cout<<"\n enter the matrix value \n"; for(int i=0;i<3;i++) { for(int j=0;j<3;j++) { cin>>a[i][j]; } } }

  32. void matrixvector::getvector(void) { cout<<"\n"; cout<<"\n enter the vector :"; for(int k=0; k<3;k++) { cin>>b[k]; } } int multiply(matrixvector mv) { cout<<"matrix - vector multiplication \n"; cout<<"\n the vector \n"; for(int m=0;m<3;m++) { cout<<"\n"; cout<<mv.b[m]; } cout<<"\n the matrix \n"; for(int i=0;i<3;i++) { for (int j=0; j<3; j++) { cout<<mv.a[i][j]; cout<<"\t"; }

  33. cout<<"\n"; } for(int e=0;e<3;e++) { for(int d=0;d<3;d++) { mv.c[e]=mv.c[e]+mv.a[e][d]*mv.b[d]; }} cout<<"\n the result is \n"; for(int n=0;n<3;n++) { cout<<mv.c[n]; cout<<"\n"; } return 0; }  int main() { clrscr(); matrixvector mv; mv.getvector(); mv.getmatrix(); multiply(mv); getch(); return 0;}

  34. const member functions A function, which guarantees not to modify the invoking object. If the body of the const function contains a statement that modifies the invoking object, the program does not compile. One exception here is the mutable member. A mutable data member can be modified by const function.

  35. void PrintDetails()const { cout <<rollno; cout <<name; cout << address; rollno=4 //error } If rollno definition is changed to mutable int rollno; in the student class ,then there will not be an error.

  36. Volatile functions A member function invoked by a volatile object. A volatile object ‘s value can be changed by external parameters which are not under the control of the program.

  37. volatile member functions. Declare a member function with the volatile specifier to ensure that it can be called safely for a volatile object: class B { int x; public: void f() volatile; // volatile member function }; int main() { volatile B b; // b is a volatile object b.f(); // call a volatile member function safely } The object b is declared volatile. Calling a non-volatile member function from this object is unsafe, because b's state might have been changed by a different thread in the meantime. To ensure that f() can be called safely for a volatile object, it's declared volatile too.

  38. Pointers and objects int x = 10; int *p; p = &x; p gets the address of x in memory. p 10 x

  39. What is a pointer? int x = 10; int *p; p = &x; *p = 20; *p is the value at the address p. p 20 x

  40. What is a pointer? Declares a pointer to an integer int x = 10; int *p = NULL; p = &x; *p = 20; & is address operator gets address of x *dereference operator gets value at p

  41. Allocating memory using new Point *p = new Point(5, 5); new allocates space to hold the object. new calls the object’s constructor. new returns a pointer to that object.

  42. Deallocating memory using delete // allocate memory Point *p = new Point(5, 5); ... // free the memory delete p; For every call to new, there must be exactly one call to delete.

  43. Using new with arrays int x = 10; int* nums1 = new int[10]; // ok int* nums2 = new int[x]; // ok Initializes an array of 10 integers on the heap.

  44. A pointer can point to an object created by a class. • Object pointers are useful in creating objects at run time. student s1; student *ptr = &s1; s1. getdata(); s1.show(); equivalent to ptr->getdata(); ptr-> show(); or (*ptr).show(); • we can also create the objects using pointers and new operator student *ptr = new student; • This allocates enough memory for the data members in the object structure and assigns the address of the memory space to ptr. • We can also create an array of objects using pointers. student *ptr = new student[5];

  45. constant objects const student s1(x,y); // object s1 is constant • Any attempt to modify the values of x and y will generate compile time error. • A constant object can call only constant member functions. void PrintDetails()const { cout <<rollno; cout <<name; cout << address; }

  46. nested classes • It is an another way of inheriting properties of one class into another. • From this we can understand that an object can be collection of many other objects, that is a class can contain objects of other classes as its members . class alpha(…); class beta(…); class gamma { alpha a1; beta b1; }; All objects of gamma class will contain the objects a1 and b1. This kind of relationship is called containership or nesting.

  47. local classes • Classes can be defined and used inside a function or a block. Such classes are called local classes. void test(int a) //function { … .. class student //local class {.. ….. //class definition … }; … … student s1(a); //create student object …. … } Local classes can use global variables and static variables declared inside the function. Enclosing function cannot access the private member of a local class.

More Related