Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex.

Slides:



Advertisements
Similar presentations
Lesson 13 Introduction to Classes CS1 Lesson Introduction to Classes1.
Advertisements

Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Chapter 7: User-Defined Functions II
Classes: A Deeper Look Systems Programming.  constconst  const objects and const member functions   Composition   Friendship  this  this pointer.
Class and Objects.
Classes & Objects classes member data and member function access control and data hiding instantiation of objects class constructor and destructor objects.
Chapter 14: Overloading and Templates
Classes: A Deeper Look Systems Programming.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
1 Classes and Objects. 2 Outlines Class Definitions and Objects Member Functions Data Members –Get and Set functions –Constructors.
More Classes in C++ Bryce Boe 2012/08/20 CS32, Summer 2012 B.
Review of C++ Programming Part II Sheng-Fang Huang.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 2.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Learners Support Publications Classes and Objects.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Concordia TAV 2002 Comp5421_421 Comp5421 Object Oriented Programming Using C++ Efficiently Lecture 4 (2) Tianxiang Shen Summer 2002 Department of Computer.
 Classes in c++ Presentation Topic  A collection of objects with same properties and functions is known as class. A class is used to define the characteristics.
CONSTRUCTORS AND DESTRUCTORS Chapter 5 By Mrs. Suman Verma PGT (Comp.Sc)
More C++ Features True object initialisation
Chapter 9 Classes: A Deeper Look, Part I Part II.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
CSI 3125, Preliminaries, page 1 Class. CSI 3125, Preliminaries, page 2 Class The most important thing to understand about a class is that it defines a.
1 CSC241: Object Oriented Programming Lecture No 05.
Functions, Scope, and The Free Store Functions Functions must be declared by a function prototype before they are invoked, return_type Function_name(type,
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
1 Mr. Muhammad Hanif Lecturer Information Technology MBBS Campus Dadu University of SIndh.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look, Part 1.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Review of Function Overloading Allows different functions to have the same name if they have different types or numbers of arguments, e.g. int sqr(int.
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
CS162 - Topic #6 Lecture: Pointers and Dynamic Memory –Review –Dynamically allocating structures –Combining the notion of classes and pointers –Destructors.
Learners Support Publications Constructors and Destructors.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Copyright © 2002 Pearson Education, Inc. Slide 1.
Operator Overloading What is operator overloading? Most predefined operators (arithmetic, logic, etc.) in C++ can be overloaded when applied to objects.
Constructors and Destructors
Procedural and Object-Oriented Programming
Chapter 7: User-Defined Functions II
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
CISC181 Introduction to Computer Science Dr
CS410 – Software Engineering Lecture #11: C++ Basics IV
Introduction to Classes
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Chapter 5 Classes.
Introduction to Classes
Structs and Classes Static Class Members Recall the following
Constructors and Destructors
Classes and Objects.
9-10 Classes: A Deeper Look.
Recitation Course 0603 Speaker: Liu Yu-Jiun.
CS410 – Software Engineering Lecture #5: C++ Basics III
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Structs and Classes Structs A struct can be used to define a data structure type as follows: struct Complex { double real, imag;} // specifying a Complex type of objects void assign(Complex& w, double r, double i){w.real = r; w.imag=i;} Complex add(Complex a, Complex b){ Complex temp; temp.real = a.real + b.real; temp.imag = a.imag + b.imag; return temp;} main(){ Complex x,y,z; assign(x,1.15,2.0); assign(y,0.01,0.0); z = add(x,y);….} For data encapsulation, a struct can be used like a class, struct Complex{ private: double real,imag; public: assign(double r, double i){real = r; imag = i;} // similar to assign() above? Complex add(Complex a){ Complex temp; temp.real = real + a.real; temp.imag = imag + a.imag; return temp;} } main(){Complex x,y,z; x.assign(1.15,2.0); y.assign(0.01,0.0); z = x.add(y);….}

Structs and Classes What is the difference between a struct and a class ? A struct members are public by default, whereas class member are private by default Example: a linked list class // define the structure of a node in the linked list struct Node { int val; Node * next;}// if class is used the key word public is needed class Llist{// the linked list class Node *list; // a list of Nodes public: Llist(){list = 0;} // create an empty list Llist(Node *y){ list = y; y->next=0;}// val and next are public // if struct Node was a class with no public section, the following statement: // friend class Llist; can be added to class Node in order to make the Llist access val // and next of any Node type object, i.e. declaring Llist as a friend class of class Node // makes private members of Node accessible by objects declared in Llist void add_node(Node *y);// adds a node to the list void print(); }; // print the elements of the list

Structs and Classes Class Declarations class Class_Name { // private is the default // 1. declarations of member data: can be constants, references, pointers, variables, // objects, of other previously defined classes, and pointer or references of the class // being defined. For example, Class_Name *x; Class_Name &y; // 2. declarations of member functions: these are private member functions, // the above private data and member functions can only be accessed by member // functions of this class and by friend classes and friend functions public: // 1. declarations of public member data // 2. declarations of public member functions: these include constructors, // destructors, and other functions defining the behavior of the class objects // the public member data and member functions can be accessed by objects of this // class declared in other parts of the program

Structs and Classes Class Member declarations 1. No initializers are allowed for data members, e.g., class List { int Max = 10; // Error no initialization allowed.. why ? the class is only a type specifier, no memory is allocated to List. 2. Member functions should be declared by function prototypes and defined in a.cpp file carrying the name of the class. Only simple one line functions should be defined when declared in the class. 3. Member functions can be declared as constants as follows: class list {int I; public: int function_name(viod) const; // A constant function can not modify any // data member } int List :: function_name(viod){.. return I; …}// I can be accessed read-only and // can not be modified. Constant functions provided another level of protection

Structs and Classes Class scope Names of member data and member functions are local to the class, and can be put in any order, e.g., int j = 10;// j is global or has a file scope Class X{ int i; // i has a class scope, void fun(){ i = 0; j = :: j * 100; // the first j is local and is defined below ……}// the second j is the global j defined above int j; // j has a class scope, j is defined after being referenced above fun2(); // fun2() is declared } X::fun2(){……} // This is used to define the body of a member // function of X outside of the class declaration block X::i = 0; // illegal and will cause a compilation error int y = X::j; // Error, data members can not be used without an object X a; // a is an object of type X; int y = a.j; // OK if j is a public data member

Structs and Classes Class Scope (cont.) Classes can be nested, i.e., a class can be defined within the scope of another class, e.g. Class A {// class A has a global scope………} Class X{ int i; // class X has a global scope and i has a class scope within X Class Y{ fun1();. // Y has a class scope within X, fun1() is a member of Y int j; }// Y has its own scope, members of X cannot access members of Y // and members of X are not accessible by members of Y Y objy; // objects of type Y can be declared as members of class X A obja; // objects of type A can also be declared as members of X fun(){Y obj1; i = 0; // obj1 is a local object within fun() Class Z{….// Z has a local scope in fun() and can not be visible outside …..}// the bodies of member functions of Z must be defined within // Z and can not be defined outside Class Y or anywhere else Z objz; // objects of type Z can only be declared within fun() }// end of class X declaration X::Y objy1;// objects of type Y can be declared outside X if Y is public in X X::Y::fun1(){….//define the body of fun1(), a member of class Y}

Structs and Classes Class Scope (cont) Example on Nested Classes: Class Node{….// a global node class} Class Llist{ Public: struct Node {// Node is declared in the public section of Llist int val; Node * next; // public data members of Node Node(int i); } Llist() {list = 0}; // constructor function of list Private: Node *list; } llist::Node::Node(int i){val = i;} Node::Node(){..//constructor function of the global Node class} main(){ Llist::Node x(10);// Ok since Node is public within Llist Llist::Node *ptr = new Llist::Node(5); // also OK

Structs and Classes Constructor functions Used for members initialization, must be used to initialize references and constants If constructors are not used, data members can be initialized as follows: Class Date{ // a data only class Public: unsigned month, day, year;}// data member must be public main(){ Date x = {9,24,96};// array style initialization Date y; // y can also be initialized as follows y.month = 9; y.day = 25; y.year = 96; } With constructors, the above can be done as follows Class Date{ unsigned month,day,year;// private data members Public: // Notice that constructor functions should not have a return_type Date(unsigned m=1;unsigned d=1;unsigned y=2000){ month=m; day=d; year=y;}// Date() is called automatically when //objects are instantiated, may have default arguments, no //default constructors are supplied by the system

Structs and Classes Constructor functions (cont.) Initializing constants and references Constants and references with a class scope must be initialized by the constructor function of their class. The initialization must occur in the init_list of the constructor function. A constructor function have the following syntax, Class_Name(argument_list):init_list{….body} Example: Typedef char* Name; class Customer _Data{ Name& Customer; const long SS_No; public: // the constructor function must initialize the above members Customer_Data(Name& x, long a): Customer(x), SS_No(a){} // the init_list consists of a list member_identifier(initial_value) // separated by commas // the above can be done for any data member, not only for references and constants

Structs and Classes Destructor functions - is a compliment of the constructor function having the same name of the class preceded by a ~ character. - Used in classes where objects are allocated using dynamically allocated storage - It is automatically invoked when an object of the class goes out of scope, or is deleted using delete - The code body of this function should de-allocate all dynamically allocated storage for a class object -A destructor function receives no arguments, and returns no value, and overloading is not allowed - Explicit invocation:

Structs and Classes Static Class Members Recall the following A static global object (i.e., an object with a file scope) has no external linkage, i.e., it cannot be in any other file A static local object (i.e., an object with a function or a block scope) is not destroyed upon function or block exit A Static data member of a class is shared by all instantiated objects of the class (all objects of the class share a single instance of the static data member) Class X { int j; // every object of class X have have its own instance of j static int I; // A static data member is declared, only one instance of I // will be defined and shared by all objects of class X. } // the static member I is only declared above and must be defined in a.cpp // file before it can be used (in X.cpp or in main_program.cpp) as follows

Structs and Classes Static Class Members(cont.) int X::I = 10;//the instance of I is defined and initialized, if the member is not // initialized, it will be initialized to zero by default main(){ X a,b,c; // instantiate three objects of type X a.j = 100; b.j = 10; c.j = 5; // assume j is in the public section of X a.I = 10; // also assumes s I is public in X, //the above is the same as b.I=10; or c.I=10 since I is shared by all objects X::I=100;// the class name can also be used to reference I } j = 100j = 10j = 5 ab c X::I

Structs and Classes Static Class Members(cont.) can be used for 1. Storing constant values or structures used by objects of the class 2. Passing data from any object of the class to other objects of the class 3. Storing results computer by collaboration among objects of the class The above considerably reduce the need for global variables Example: Fixed lenght vectors Class Vector{……. static const int lenght; // the declaratoin of length …..} const int Vector::length = 100;// the definition of length Vector::Vector(int n = length) {…….} The above shows that a static data member can appear as a default argument of a member function

Structs and Classes Static Class Members(cont.) Example: Counting the number of objects class X{… static int count; public: X(){…..count++;…..} static int get_count(){return count;}// a static member function is a // function which may only access static data members } main(){ X a,b,c; cout << “no. of objects created =\t” << X::get_count(); // Note a static member function can be invoked using the class name }

Structs and Classes Static Class Members(cont.) A static data member can be an object of the class in which it is a member Class X{…. X* ptr; // OK X& ref; // OK X obj; // Error, a data member of a class can not have the class type static X obj; // OK since obj is a static data member } Example:The human race class class Human{…. static Human Adam, Eve; // these static objects are shared by all objects // of this class } A pointer to a static data member is defined as follows Human * ptr_to_Adam = & Hunam::Adam;

Structs and Classes The this pointer A special pointer used in member functions of a class as a pointer to the object instance for which the member function was invoked. Class X { …. int I; public: int get_I(){return I;}// I can be referenced by this->I X increment_I(){ I++; return (*this);}// the pointer is implicitly declared // in every member of the class by X* const this } void f(X a, X b){… int I = a.get_I(); int j - b.get_I(); cout << a.increment_I().get_I(); }// a.increment returns back the instance of object a

The this pointer (cont.) A doubly linked list