1 / 44

C++ Class Members

C++ Class Members. Class Definition class Name { public: constructor(s) destructor function members data members protected: function members data members private: function members data members };. C++ Class Members. Class Definition - Data Members Data Members

margie
Télécharger la présentation

C++ Class Members

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. C++ Class Members • Class Definition • class Name • { • public: • constructor(s) • destructor • function members • data members • protected: • function members • data members • private: • function members • data members • }; 1 February 2006

  2. C++ Class Members • Class Definition - Data Members • Data Members • It is important to note ….. • Each class instance gets distinct copies of all data members 1 February 2006

  3. C++ Class Members • Class Definition - Data Members • class MyClass • { • public: • MyClass() { myValue = 10; } • int getMyValue () { return myValue;} • int setMyValue (int aValue) { myValue = aValue;} • private: • int myValue; • }; • int main(void) • { • MyClass inst0, inst1; • inst1.setMyValue(20); • cout << inst0.getMyValue() << endl • << inst1.getMyValue() << endl; • return 0; • } 1 February 2006

  4. C++ Class Members • Class Definition - Function Members • Function Members • Unlike data members • Only one instance of each function member exists for a class • Unless the function is declared inline 1 February 2006

  5. C++ Class Members • Class Definition - Function Members • Function Members • If only a single instance….. • How are data members which function manipulates • bound to the function instance????? • What is not shown • The member function has a hidden argument • The arg is a pointer to the object that was sent the message • Pointer is identified by the keyword this 1 February 2006

  6. C++ Class Members • Class Definition - Function Members • Function Members • The this pointer • Has type ClassType • Contains the address of the class instance through which the member function was invoked • Starting address is same as the address of the first variable in the class structure 1 February 2006

  7. C++ Class Members • Class Definition - Function Members • Function Members • Every nonstatic function member has a pointer implicitly declared • ClassName * const this; • this is initialized to point to the object for which the member • function was invoked • Because this is declared const • It cannot be changed • Object pointed to can 1 February 2006

  8. C++ Class Members • Class Definition - Function Members • Function Members • Since this is a pointer to the beginning of the class structure • One can select elements using pointer notation • this -> myElement • To refer to the entire instance….. • *this • return *this • Will produce a copy of the instance as the return value 1 February 2006

  9. C++ Class Members • Class Definition - Function Members • class Link • { • public: • void append (Link* aLink); • void setPrev (Link* aLink); • private: • Link* next; • Link* prev; • }; • void Link :: append(Link* aLink) • { • next = aLink; • aLink -> setPrev(this); • return; • } Next Li Li+1 Previous this 1 February 2006

  10. C++ Class Members • Managing Storage - Object Creation • When a C++ object is created 2 events occur…….. • Storage is allocated for the object • The constructor is called to initialize the storage • Storage allocation occurs in several ways and at different times 1 February 2006

  11. C++ Class Members • Managing Storage - Object Creation • Static Storage • Allocated when the program begins • Constant for the life of the program • Stack • Storage allocated on the stack when an execution point is • reached - Opening curly brace. • Released at the complementary execution point - closing curly • brace. • Heap - Free Store • Storage is dynamically allocated from the heap at runtime 1 February 2006

  12. C++ Class Members • Managing Storage - Object Creation • Declaration • Introduces a name • Tells the compiler what the name means • Usually go into header files • Definition • Allocates storage for the name 1 February 2006

  13. C++ Class Members • Managing Storage - Object Creation • Variable • The compiler determines the variable size and generates space • If there is an initializing value, the value entered into that storage • Compile time storage usually allocated at the opening brace • Constructor not called until sequence point where object defined • Auto storage will be allocated on the stack • Function • Compiler generates code and allocates storage to hold the code • Storage for function has an address that can be produced using • Function name with no arg list • Address of operator • Usually go into implementation files 1 February 2006

  14. C++ Class Members • Managing Storage - Linkage • Linkage • Describes storage to represent an identifier as seen by linker • Internal • Storage created for identifier for file being compiled • Name may be used in other files without conflict • External • Single piece of storage for all files being compiled • Accessed from other files by keyword extern • Variables defined outside functions • Inline function definitions default to external linkage • Automatic (local) Variables • Exist on the stack while function being called • Auto variables have no linkage 1 February 2006

  15. C++ Class Members • Managing Storage - Inline Functions • Inline Functions • C++ permits specification of inline functions • Identified by keyword inline … the definition of function follows • syntax • inline type functionName (argsi) { body } • When inline definition encountered • No code generated • Code remembered and substituted for each function call 1 February 2006

  16. char a static int b class M m2 char a m0 char a int b m3 char a m1 char a C++ Class Members • Static Data Members • A class is a type not a data object • When an instance of a class is defined….. • The instance gets a copy of all data members • If data member declared static • Single copy • Shared by all instances of the class • Smalltalk • Pool variables 1 February 2006

  17. C++ Class Members • Static Data Members • syntax • Declaration • static type varName; • Definition • type ClassName :: varName < = value > • Static member exists even if no class instances exist • Remain in scope of class • Can only be accessed from outside if declared public 1 February 2006

  18. C++ Class Members • Static Data Members • Storage for a static variable • Must be explicitly reserved and initialized • Static can be declared within a class • Definition and initialization must occur outside Class • Can be only single definition • Static (nonclass) variables • Initialized to 0 by default • Static class variables • Cannot be initialized by the constructor 1 February 2006

  19. C++ Class Members • Initializing Static Data Members... • class SimpleClass • { • public: • SimpleClass () {} • SimpleClass (int aValue){myValue = aValue;} • // static char myChar = 'c'; This is illegal • static char myChar; • private: • static int myValue; • }; • // Define and initialize the static variables • int SimpleClass::myValue = 10; • char SimpleClass::myChar = 'a'; 1 February 2006

  20. C++ Class Members • Static Data Members • Static Data Member • Can appear as a default arg to a member function • Non-static Data Member • Cannot appear as a default arg to a member function • Within a class body….. • int a; • static int b; • int f1 ( int myValue0 = a ); // illegal • int f2 ( int myValue1 = b ); // ok 1 February 2006

  21. C++ Class Members • Static Data Members • A static data member can be an instance of the class of which it is a • member….. • A non-static can only point to an instance of it’s class. • Within a class body • class F1 • { • public: • F1 *a; // ok • static F1 b; // ok • F1 c; // illegal • }; 1 February 2006

  22. C++ Class Members • Const Data Members • Class data members can be specified as const • Consequence • Storage always allocated and must be initialized at point of • definition • Initialization must occur in the constructor • Implemented via the initialization list • Storage not allocated until instance created…... • At that time, the const must be • Created • Initialized • Const variable persists for the lifetime of the instance 1 February 2006

  23. C++ Class Members • Static Function Members • Function members can be declared static • A static function has no this pointer • static function can access • Directly • static members • enums and typedefs • Indirectly • Regular members via . or -> through an explicit object 1 February 2006

  24. C++ Class Members • Static Function Members • class SimpleClass • { • public: • //static int getMyNumber() {return myNumber;} requires an object • static int getMyNumber() { return myValue;} • static int getMyStuff(SimpleClass *myClass) {return myClass->myNumber;} • static int getMyVal() {return myValue;} • static char myChar; • char myLetter; • private: • static int myValue; • int myNumber; • }; • int SimpleClass::myValue=10; • char SimpleClass::myChar = 'a'; 1 February 2006

  25. C++ Class Members • Static Function Members • int main() • { • SimpleClass myClass, yourClass, *myClassPtr = &myClass ; • cout << SimpleClass::getMyStuff(myClassPtr) << endl; • cout << myClass.myChar << " " << SimpleClass::myChar << endl; • return 0; • } 1 February 2006

  26. C++ Class Members • Const Function Members • The keyword const can be placed after argument list of member • function • syntax • returnType functionName ( argsi ) const { function body } • Tells compiler that function • Can only read data members • Cannot write them • Member functions declared const • Can be called for non-const objects • Non-const member functions • Cannot be called for const objects. 1 February 2006

  27. C++ Class Members • Overloading Function Members • Functions can use same name in the same scope • If signature is unique • Name plus signature • Uniquely identify function • Same holds true for member functions Same rules applied to disambiguate Must provide Implementation for each overloaded function 1 February 2006

  28. C++ Class Members • Operator Function Members • C++ defined operators can be overloaded to work on Class type • operands • Must take at least one class type argument • syntax • operator X (args) { body } • X is the operator symbol being overloaded • args - as appropriate for implementation • body - implements the function 1 February 2006

  29. C++ Class Members • Operator Function Members • Invocation • Assume + is overloaded • Infix expression syntax • A + B • A, B can be member or non-member instances • Function call syntax • A.operator+ (B) 1 February 2006

  30. C++ Class Members • Operator Function Members • Rules • Because operator functions are invoked using the same syntax • Operator functions... • 1. Must have the same number of arguments as language defined versions • 2. Must have the same precedence as the builtin operators…This cannot be overridden • 3. Cannot have default parameters • 4. Cannot override the predefined meaning 1 February 2006

  31. C++ Class Members • Operator Function Members • Limitations • Because of the operator function syntax • 1. Certain user defined operators cannot behave • analogously to built in versions • Prefix version • operator++ () {} • Postfix version • operator++ (int) {} • 2. Some operators cannot be overloaded. , ?: :: . * • 3. Some operators must be members only =, [ ] , ( ), -> 1 February 2006

  32. C++ Class Members • Overloading Operators • class Complex • { • public: • int im, re; • Complex(int r=0, int i=0):re(r), im(i) { } • Complex operator+ (Complex a1) {return Complex(re+a1.re, im+a1.im);} • Complex& operator++ () • { • re += 1, im += 1; • cout << “prefix" << endl; • return Complex(re -1, im -1); • } • Complex& operator++ (int) • { • re+=1, im+=1; • cout << "postfix" << endl; • return *this; • } • }; 1 February 2006

  33. C++ Class Members • Operator Function Members • Member • Left hand operand must be an instance of class overloading • the operator • Unary • x.operator@() • x is class instance • Binary • x.operator(y) • x operator@ y • x is class instance 1 February 2006

  34. C++ Class Members • Operator Function Members • Non-Member • If operator requires left hand operand of a different type….. • Must use non-member syntax • Must be declared friend if the operator requires access to • protected or private members • Unary • operator@(x) • Binary • operator@(x,y) • x operator@ y 1 February 2006

  35. C++ Class Members • Operators in Action • The Copy Constructor and the Assignment Operator • There are many occasions when a copy of an object is needed • Object passed by value • x.func(y) • A copy of y is made and passed • Object returned by value • Object initialized by another object • ClassName x1 = x2 • A copy of x2 is made • Object assigned to another object • x1 = x2 • x2 is copied to x1 and • x1 is destroyed 1 February 2006

  36. C++ Class Members • Operators in Action • The Copy Constructor • A constructor that….. • Takes a reference to an object of the same class as an • argument • Performs initialization on newly created objects • Used by compiler to copy objects by value • syntax • class X ( const class X& ) • class X ( class X& ) 1 February 2006

  37. C++ Class Members • Operators in Action • The Copy Constructor • If a copy constructor is not defined • Shallow bitwise copy performed - memcpy • If a copied object uses new to allocate memory when created • One must write a copy constructor • Copy constructor need only be written • If class object is passed by value • To prevent pass by value • Define a private copy constructor 1 February 2006

  38. C++ Class Members • Operators in Action • The Assignment Operator - operator=() • Called when one initialized object is to be assigned to a second. • The operator must serve as a destructor to the assignee object. • Can have a return value… • The most common is *this • Is not called for the declarations such as • ClassName object1 = object2 1 February 2006

  39. C++ Class Members • Class Members - Friends • A class Definition…. • Provides 3 levels of access to data and function members • public • protected • private Closed Open 1 February 2006

  40. C++ Class Members • Class Members - Friends • C++ provides means for more liberal access to non-public members • under specified set of conditions….. • Nonmember designated as a friend of the class • Class friend is designated by Keyword friend Followed by class name 1 February 2006

  41. C++ Class Members • Class Members - Friends • Once an object is designated as a friend…. • It has access to non-public members as if they were public • If B is designated as friend of A • B can access A’s non-public members • A cannot access B’s 1 February 2006

  42. C++ Class Members • Class Members - Friends • Friend may be: • 1. Class • friend class X; • 2. A particular function • friend int sub (int y); • 3. A particular class member • friend int Mult::get(); 1 February 2006

  43. C++ Class Members • Class Members - Friends • A friend does not have a this pointer unless it is a member function in • its own right • Question: • If it is a member function which this pointer does it have • Class A a; • Class B b; • Let B be declared as a friend of A • The this pointer of a function bFunct() contains • the address of the class instance b 1 February 2006

  44. C++ Class Members • Class Members - Friends • Caveats and Problems,,, • Friends can have access to everything … this defeats data • hiding. • Introduces extra coupling between classes. • Permits change of internal state from the outside. • Should use member functions not friends to change state. 1 February 2006

More Related