Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 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);….}

2 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

3 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

4 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

5 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

6 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}

7 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

8 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

9 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

10 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:

11 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

12 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

13 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

14 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 }

15 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;

16 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

17 The this pointer (cont.) A doubly linked list


Download ppt "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."

Similar presentations


Ads by Google