230 likes | 385 Views
C++ Classes. Fred Kuhns Computer Science and Engineering Washington University in St. Louis. Some definitions. Translation unit (TU): what is processed by the compiler
E N D
C++ Classes Fred Kuhns Computer Science and Engineering Washington University in St. Louis
Some definitions • Translation unit (TU): what is processed by the compiler • The “one-definition rule” or ODR: Each class (or enumeration, template, function etc) must be defined exactly once in a program • it is possible to have two definitions if they are in different TUs and are identical … but it is best to avoid this situation! • Across translation units: • Use name of functions, classes, templates, variables, namespaces and enumerations consistently • declare each class, …, consistently. Note the extern keyword asserts that what follows is a declaration and not a definition. • Linkage: • eternal linkage: a name that can be used in TUs other than the one in which its is defined • internal linkage: only available in the immediate TU. • An inline function must be identically defined in every TU in which it is used. Put in a header or other (.i) include file. • const and typedefs by default have internal linkage. If you want them to be global then place in a header file. CS422 – Operating Systems Concepts
What to put in header files (see [Stroustrup])? Yes • Named namespaces • Type definitions • Template declarations • Template definitions • Function declarations • Inline function definitions • Data declarations • Constant definitions • Enumerations • Name declarations • Include directives • Macro definitions • Conditional compilations directives • Comments No • Ordinary function definitions • Data definitions • Aggregate definitions • Unnamed namespaces • Exported template definitions CS422 – Operating Systems Concepts
Class Intro • type: concrete instance of a concept and is said to model the concept. • concept: places a set of requirements on a type • A class is a user defined type, want to separate implementation details from properties • Concrete type: simple, not derived • typical concrete Class structure: class Date { int d, m, y; public: // default is private -- constructors -- -- access methods (const)-- -- manipulator methods -- -- implicit or explicit copy operators -- -- exception class – } • member functions may be defined in separate context (for example the .cc file with the class declaration in a .h file). If a member function is defined in the declaration then it will be inlined. CS422 – Operating Systems Concepts
Access control • Access control: use public or private keywords (default is private). A struct is the same as a class with all members public. Non-member functions can not access private members. class Date { public: Date(int m, int d, int y); … private: int _m, _d, _y; } CS422 – Operating Systems Concepts
static class members • A static member is part of the class but not of any particular object (instance of the class). • static object referenced using class name, Date::default_date • Must define static members someplace, usually outside of class. • non-const data members must be initialized outside of class class Date { int _d, _m, _y; static Date default_date; public: Date(…); … static void set_default(int,int,int); }; Date::Date(int m, int d, int y) { _d = d ? d : default_date._d; _m = m ? _m : default_date._m; _y = y ? _y : default_data._y; } Date Date::default_date(01,01,2004); void Date::set_default(int m, int d, int y) { Date::default_date = Date(m, d, y); } CS422 – Operating Systems Concepts
Constant member functions • You will generally have a set of methods whose only purpose is to access object data. class Date { … int day() const; } int day() const { return _d; }; • The const indicates the method will not modify the object’s state. • note, the const keyword is part of the member functions type and must be repeated when defined • A non-const method can not be invoked on a const object but a const member function can. CS422 – Operating Systems Concepts
self reference • All object member functions (non-static) are invloked with a pointer to itself • non-const member function: X * const this; • const member function; const X *const this; • the “this” pointer is implied when access member fields within a member function • You can use this to return a reference to the ojject Date& Date::add_year(int n) { if (…) {…} // check for leap year _y += n; // this-> implied return *this; } CS422 – Operating Systems Concepts
Helper functions • generally you should only place into class definitions those methods which need direct access to object state. • helper functions are those functions which can be defined outside of the class. Usually either in the same file or in a utility library. • This may include some of the overloaded operators. CS422 – Operating Systems Concepts
Creating objects • named automatic object • free-store object (new/delete) • nonstatic member object • array element • local static object • global, namespace, or class static object • temporary object • indirect instantiation: allocate memory then define it to contain an object • union member CS422 – Operating Systems Concepts
Constructors • A class constructor has the same name as the class Date { Date(int, int, int); // class constructor Date(); // default constructor Date(int m, int d=0, int y=4); // default args … } Date::Date(int m, int d, int y) { _m = m; // always required _d = d ? d : today._d; // 0 is invalid, today is global _y = y; // by default a valid year is given } • establishes invariant for the class (what must always be true) CS422 – Operating Systems Concepts
default constructor • Takes no arguments • compiler will attempt to generate one is not defined • built-in types are not initialized to preserve compatibility with C • if class contains consts or references then a default constructor can not be defined CS422 – Operating Systems Concepts
Destructors • while constructors create new instances of a class, a destructor is used to “clean up” after an object is no longer needed. • ~X : destructor for object X • Implicitly called when object is destroyed • Common scenario: constructor allocates some resources (memory) then a destructor is defined to release this memory when object is deleted. CS422 – Operating Systems Concepts
More on constructors/destructors • Destructor example • Constructor allocates memory for string • Destructor must deallocate memory Student::Student (char *n) { if (n == null) { name = new char[DefBufSz]; *name = ‘\0’; else { name = new char[strlen(n)+1]; strcpy(name, n); } } Student::~Student() { cout << “Calling destructor\n”; delete [] name; } class Student { char *name; … public: Student(char *n=null); ~Student(); … } CS422 – Operating Systems Concepts
Copy Objects • Default copy semantics; memberwise copy • Copy initialization: X::X(const X&) • Copy assignment X& operator-(const X&); • Example: (0) void fn() { (1) Student s1(“Fred”); // (2) Student s2 = s1; // copy initialization (3) Student s3; // default constructor (4) s3 = s2; // copy assignment (5) } // call destructors • Do you see any problems here? • memory leak • delete called on same memory 3 times class Student { char *name; … public: Student(char *n=null); ~Student(); … } CS422 – Operating Systems Concepts
Fixing the problem Student::Student (char *n) { if (n == NULL) { name = new char[DefBufSz]; *name = ‘\0’; else { name = new char[sizeof(n)+1]; strcpy(name, n); } } Student::Student(const Student& s) { name = new char[strlen(s.name)+1]; strcpy(name, s.name); } Student& Student::operator=(Student& s) { if (this != &s) { delete [] name; name = new char[strlen(s.name)+1]; strcpy(name, s.name); } return *this; } Student::~Student() { cout << “Calling destructor\n”; delete name; } • Define copy constructors. • Copy assignment: • check for self-assignment, delete old elements, initialize and copy new elements. class Student { char *name; … public: Student(char *n=NULL); Student(const Student&); Student& operator=(const Student&); ~Student(); … } CS422 – Operating Systems Concepts
new • The operator new allocates memory from the free store • the operator delete frees memory allocated by new • you must free all memory allocated (no garbage collection) • it is an error to call delete two or more times on the same memory location • you can overload (redefine) these operators, the placement syntax void *operator new(size_t, void *p) {return p;} void *buf = reinterpret_cast<void *>(0xf00f); X* p2 = new(buf)X; CS422 – Operating Systems Concepts
Initializing Objects • Classes may have other classes as members • specify class constructor parameters in the members initializer list class Grades {…Grades(string);...}; class Student { char *name; Grades g; public: Student(char *n=NULL) : name(0), Grades(“A”) { … } } • constructors for members in initializer list are • called before entering the constructors body • called in order they are listed in class declaration • The destructor for the member objects are called after the objects destructor • Must use initialize list for reference members, consts and any member objects without default constructors. CS422 – Operating Systems Concepts
initializing • Static integral constants may be initialized within class declaration by a constant expression. static const int MAX = 100; • you must also define outside of class const int MAX; // but don’t reinitialize • or you can use enumator enum {MAX = 100, MIN = 0, …}; • You can define an array of a class T iff T has a default constructor. Further, the destructors for all elements in the array are called when the array is deleted. delete X; // delete element X delete [] X; // delete array X CS422 – Operating Systems Concepts
Temporary Objects • Temporary objects may be created during the evaluation of an expression. • it is destroyed at the end of the expression // s1, s2 and s3 are of type string const char* cs = (s1+s2).c_str(); cout << cs; if (strlen(cs=(s2+s3).c_str())< 8 && cs[0] == ‘a’) { … do something … } • temporary can be used to initialize a const reference or named named object const string& s = s1 + s2; // const reference string str = s1 + s2; // named object string& sx = s1 + s2; // error • Another way to create a temporary object: add_record(Student(name)); CS422 – Operating Systems Concepts
Polymorphic Types • See separate presentation on polymorphism CS422 – Operating Systems Concepts
Multiple inhetitance • Overload resolution is not applied across class scope boundaries. So if two different base classes define a function with the same name, then you have an ambiquity. • Be explicit, Base1::fn() or Base2::fn() • use a using-clause, using Base1::fn(); using Base2::fn() • What about replicated base classes? • ambiguities related to which base is being referenced • you should write an overriding function in the derived class • Virtual Base Classes • ensures only one copy of base object is constructed. • initialization of virtual base class is responsibilty of the most derived object. CS422 – Operating Systems Concepts
Run-Time Type Information • dynamic_cast : if p is a pointer to class T* then the address is retured, otherwise 0. Alternatively, if p a reference to type T (i.e. T&) then the assignment is made, otherwise can exception is thrown. • Restricting: type T must be a polymorphic type dynamic_cast<T*>(p) dynamic_cast<T&>(p) • static_cast<T*>(p) does not exampme the underlying type. • There is also a typeid() operator that returns type information (including a name string) • if polymorphic type then actual derived type is returned • otherwise the expression type is returned. CS422 – Operating Systems Concepts