0 valutazioniIl 0% ha trovato utile questo documento (0 voti)
23 visualizzazioni7 pagine
Members and base classes of a struct are public by default, while in class, they default to private. Static members can be declared using the storage class specifier static in the cl ass member list. A reference is the object. It is not a pointer to the object, nor a copy of the object.
Members and base classes of a struct are public by default, while in class, they default to private. Static members can be declared using the storage class specifier static in the cl ass member list. A reference is the object. It is not a pointer to the object, nor a copy of the object.
Copyright:
Attribution Non-Commercial (BY-NC)
Formati disponibili
Scarica in formato TXT, PDF, TXT o leggi online su Scribd
Members and base classes of a struct are public by default, while in class, they default to private. Static members can be declared using the storage class specifier static in the cl ass member list. A reference is the object. It is not a pointer to the object, nor a copy of the object.
Copyright:
Attribution Non-Commercial (BY-NC)
Formati disponibili
Scarica in formato TXT, PDF, TXT o leggi online su Scribd
The members and base classes of a struct are public by default, while in class, they default to private. built in operators dont work on struct. 2. static - Class members can be declared using the storage class specifier static in the cl ass member list. Only one copy of the static member is shared by all objects of a class in a program. When you declare an object of a class having a static memb er, the static member is not part of the class object. A typical use of static members is for recording data common to all objects of a class. For example, you can use a static data member as a counter to store the number of objects of a particular class type that are created. Each time a new o bject is created, this static data member can be incremented to keep track of th e total number of objects. You access a static member by qualifying the class name using the :: (scope reso lution) operator. In the following example, you can refer to the static member f () of class type X as X::f() even if no object of type X is ever declared. 3. reference References are frequently used for pass-by-reference: void swap(int& i, int& j) { int tmp = i; i = j; j = tmp; } int main() { int x, y; ... swap(x,y); ... } A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object.Unlike a pointer, once a reference is bound to an objec t, it can not be "reseated" to another object. a reference should be assigned to a target at declaration time.using references, user calls can behave the same, the called function handles changing the actual values (think of swap fn as oppo sed to pointers where user function needs to pass pointers).a reference should n ever be null, so the result of new should be passed to a pointer (as it can be n ull) and hten assigned to ref. int *pint = new int; if (pint!=null) int &rint = *pint; 4. inline functions vs macros Unlike #define macros, inline functions avoid infamous macro errors since inline functions always evaluate every argument exactly once. In other words, invoking an inline function is semantically just like invoking a regular function, only faster. 5. destructor is used to release resources held by an object. destructor cannot be overloaded. Only one destructor, never takes args, never returns anything. fi rst constructed last destructed.destructor should not be explicity called. delet e on an object automatically calls the destructor and frees memory. never throw exception from destructor (while processing another exception ie during stack un winding). 6. constructor can be private - you can have named public static constructors wh ich call the private one. constructors can throw exceptions. 7. operator overloading - at least one operand of any overloaded operator must b e of some user-defined type (most of the time that means a class). 8. make the destructor virtual when someone will delete a derived class object v ia a base class pointer.if any function in the class is virtual, make the destru ctor virtual as well. 9. virtual constructor is not directly supported in C++. virtual copy constructo r can be created by making a virtual member function that calls the copy constru ctor 10. private inheritance is similar to composition but private inheritance is usu ally used to gain access into the protected members of the base class. 11. To avoid the duplicated base class subobject that occurs with the "dreaded d iamond", you should use the virtual keyword in the inheritance part of the class es that derive directly from the top of the diamond. To ensure that derived classes have only one instance of common base classes, de clare the intermediate classes to inherit virtually from the base class. 12. to read a string - cin.get(buffer, maxnumberofchars) - default delimiter is \n 13. c++ standard string class is in std::string. std::string str1("this is a str ing"); 14. pointer needs 4 bytes of mem to store address on a 32-bit machine and 8 byte s on a 64-bit machine 15. dangling pointer - when a pointer is deleted and not set to null. using it a gain can cause unpredictable results if it is not set to null. 16. with const - look to the right to determine if the int is const or ptr is. const int *pone - ptr to a constant integer int * const ptwo - constant pointer to integer const int* const pthree - constant pointer to constant integer 17. if a class method is constant that means it will not change any of the data members of the class void somefunction() const; 18. virtual functions overriden in the derived class can be used with base class pointer or reference, not with value. Mammal mammal = new Dog; mammal.speak will call mammal's method Mammal &mammal =new Dog; mammal.speak will call dog's method Mammal *mammal = new Dog; mammal.speak will call dog's method 19. private inheritance is used when there is no is-a relationship bt the code n eedds to be reused. virtual functions can be overriden in private inheritance bu t all the contents of the base class are private to the users of the derived cla ss 20. private inheritance vs aggregation -aggregation avoid the v-table overhead (performance issues) - code becomes less flexible and error pronee private inheritance allows the class to access protected members of the base cla ss adn override virtual funcs aggregation shud be used when possible 21. Methods in the base class can be called from derived class as Mammal::walk() ; 22. C++ supports casting down using the dynamic_cast operator Run time type determination - Horse* Ranch[number] Pegasus *pPeg = dynamic_cast<Pegasus *> (Ranch[i]) if (pPeg !=null) => cast successful 23. C++ supports creation of abstract classes by providing the pure virtual func tion. a virtual fnction is made pure by initializing it to zero - virtual void D raw() = 0; any class with one or more pure virtual fns is an abstract class and canot be instatiated. It is possible to provide implementation to a pure virtual fn. The function can then be called by derive classes to get common functionality. 23. operator overloading example - CDate operator ++(int) { CDate newDate (day, moth,year); AddDays(1); return newDate; } void operator+=(int ndays) { addDays(ndays)} 24. problems with macros -can be confusing when they get large as they have to be defined on one line - expanded inline so they dont appear in intermediate source code used by compil er so not available in debggers making it harder to debug - they are not type safe - If macro parameter has a postincremented variable ( like c++ ), the increment is performed two times. 25. templates allow to define a behavior that can be applied to objects of varyi ng types template <typename objectType> objectType &Getmax (const objectType & value1, const objectType & value2) { if (value1>value2) return value1; else return value2; } int nmaxvalue = GetMax<int>(nInteger1, nInteger2) or int nmaxvale = GetMax(ninte ger1, ninteger2); 26. assignment operator handles assigning one object to the other of the same cl ass. member to member copy (shallow copy) 27. implicit member fns of a class - default ctor, copy ctor, assignment operato r, default dtor, address operator 28. What is copy constructor? Constructor which initializes the it's object member variables ( by shallow copy ing) with another object of the same class. If you don't implement one in your c lass then compiler implements one for you. for example: Boo Obj1(10); // calling Boo constructor Boo Obj2(Obj1); // calling boo copy constructor Boo Obj2 = Obj1;// calling boo copy constructor 29. When are copy constructors called? Copy constructors are called in following cases: a) when a function returns an object of that class by value b) when the object of that class is passed by value as an argument to a function c) when you construct an object based on another object of the same class d) When compiler generates a temporary object 30. what is the diff between "new" and "operator new" ? "operator new" works like malloc. 31. Const keyword indicates that memory once initialized, should not be altered by a program. volatile keyword indicates that the value in the memory location can be altered even though nothing in the program code modifies the contents. for example if you have a pointer to hardware locati on that contains the time, where hardware changes the value of this pointer vari able and not the program. The intent of this keyword to improve the optimization ability of the compiler. 32. auto: the default. Variables are automatically created and initialized when they are defined and are destroyed at the end of the block containing their definiti on. They are not visible outside that block register: a type of auto variable. a suggestion to the compiler to use a CPU reg ister for performance static: a variable that is known only in the function that contains its definiti on but is never destroyed and retains its value between calls to that function. It exists from the time the program begins execution extern: a static variable whose definition and placement is determined when all object and library modules are combined (linked) to form the executable code fil e. It can be visible outside the file where it is defined. 33. What problem does the namespace feature solve? Multiple providers of libraries might use common global identifiers causing a na me collision when an application tries to link with two or more such libraries. The namespace feature surrounds a library's external declarations with a unique namespace that eliminates the potential for those collisions. namespace [identifier] { namespace-body }
34. What is an Iterator class?
A class that is used to traverse through the objects maintained by a container c lass 35. How virtual functions are implemented C++? Virtual functions are implemented using a table of function pointers, called the vtable. There is one entry in the table per virtual function in the class. This table is created by the constructor of the class. When a derived class is const ructed, its base class is constructed first which creates the vtable. If the der ived class overrides any of the base classes virtual functions, those entries in the vtable are overwritten by the derived class constructor. This is why you sh ould never call virtual functions from a constructor: because the vtable entries for the object may not have been set up by the derived class constructor yet, s o you might end up calling base class implementations of those virtual functions 36. How are prefix and postfix versions of operator++() differentiated? The postfix version of operator++() has a dummy parameter of type int. The prefi x version does not have dummy parameter. 37. Name two cases where you MUST use initialization list as opposed to assignme nt in constructors. Both non-static const data members and reference data members cannot be assigned values; instead, you should use initialization list to initialize them. 38. Can you overload a function based only on whether a parameter is a value or a reference? No. Passing by value and by reference looks identical to the caller. 39. How do you access the static member of a class? :: 40.if NestedClass is public then any code can name it as OuterClass::NestedClass . Often nested classes contain private implementation details, and are therefore made private; in Example 1, if NestedClass is private, then only OuterClass's m embers and friends can use NestedClass. When you instantiate as outer class, it won't instantiate inside class. 41. Can a copy constructor accept an object of the same class as parameter, instead of reference of the object? No. It is specified in the definition of the copy constructor itself. It should generate an error if a programmer specifies a copy constructor with a first argu ment that is an object and not a reference. MyObject a; // default constructor call MyObject b(a); // copy constructor call MyObject bb = a; // identical to bb(a) : copy constructor call MyObject c; // default constructor call c = a; // assignment operator call The copy constructor is for creating a new object. It copies a existing object t o a newly constructed object. The assignment operator is to deal with an already existing object. 42. A shallow copy of an object copies all of the member field values. This work s well if the fields are values, but may not be what you want for fields that po int to dynamically allocated memory. The pointer will be copied. but the memory it points to will not be copied -- the field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usu ally what you want. The default copy constructor and assignment operator make sh allow copies. A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. To make a deep copy, you must write a copy constructor and overload the assignment operator, otherwise the copy will point to the orig inal, with disasterous consequences. 43. A constructor cannot be virtual because at the time when the constructor is invoked the virtual table would not be available in the memory. Hence we cannot have a virtual constructor. 44. general exception handler in c++ - catch (...) 45. The C++ Standard library provides a base class specifically designed to decl are objects to be thrown as exceptions. It is called exception and is defined in the <exception> header file under the namespace std. This class has the usual d efault and copy constructors, operators and destructors, plus an additional virt ual member function called what that returns a null-terminated character sequenc e (char *) and that can be overwritten in derived classes to contain some sort o f description of the exception. int main () { try { int* myarray= new int[1000]; } catch (exception& e) { cout << "Standard exception: " << e.what() << endl; } return 0; } 46. operator overloading - cannot create a unary definition for an operator that was previously only a binary operator (ex. +). Cannot redefine an existing defi ntion of an operator overloading + -> operator+ (arguments) example - operator @(x) - @ is declared globally takes 1 param x x.operator@() - @is a class method, x is the object (1st arg) Distance Distance::operator +(Distance d2) { int f = feet + d2.feet; float i = inches + d2.inches; if (i>12){ i -=12; f++; } return Distance(f,i); }
String operator+(String ss) {
String temp; if (strlen(str) + strlen(ss.str) < SZ) {strcpy(temp.str,str); strcat(temp.str,ss.str); } return temp; } 47. smart pointer - a smart pointer is an abstract data type that simulates a po inter while providing additional features, such as automatic garbage collection or bounds checking.Smart pointers try to prevent memory leaks by making the reso urce deallocation automatic: when the pointer to an object (or the last in a ser ies of pointers) is destroyed, for example because it goes out of scope, the poi nted object is destroyed too. Several types of smart pointers exist. Some work with reference counting, others assigning ownership of the object to a single pointer. -- overloading unary, binary operator, prefix, postfix -- can u overload + operator with - -- gdb -- last 2 chaps of the pie -- virtual copy const -- templates - diff bw template and macro -- quick sort code, merge sort code -- compilation adn linking - .so and .a files