- What is the output of printf(â€Å"%dâ€Â)?
- %d helps to read integer data type of a given variable
- when we write (â€Å"%dâ€Â, X) compiler will print the value of x assumed in the main
- but nothing after (â€Å"%dâ€Â) so the output will be garbage
- printf is an overload function doesnt check consistency of the arg list – segmentation fault
- What will
happen if I say delete this? - destructor executed, but
memory will not be freed (other than work done by destructor). If we
have class Test and method Destroy { delete this } the destructor for
Test will execute, if we have Test *var = new Test()
- pointer var will still be valid
- object created by new exists until explicitly destroyed by delete
- space it occupied can be reused by new
- delete may only be applied to a pointer by new or zero, applying delete to zero = no FX
- delete = delete objects
- delete[] – delete array
- delete operator destroys the object created with new by deallocating the memory assoc. with the object
- if a destructor has been defined fir a class delete invokes that desructor
- Difference between C structure and C++ structure
- C++
places greater emphasis on type checking, compiler can diagnose every
diff between C and C++
- structures are a way of storing many different values in variables of potentially diff types under under the same name
- classes and structures make program modular, easier to modify make things compact
- useful when a lot of data needs to be grouped together
- struct Tag {…}struct example {Int x;}example ex; ex.x = 33; //accessing variable of structure
- members of a struct in C are by default public, in C++ private
- unions like structs except they share memory – allocates largest data type in memory - like a giant storage: store one small OR one large but never both @ the same time
- pointers can point to struct:
- C++ can use class instead of struct (almost the same thing) - difference: C++ classes can include functions as members
- members can be declared as: private: members of a class are accessible only from other members of their same class; protected: members are accessible from members of their same class and friend classes and also members of their derived classes; public: members are accessible from anywhere the class is visible
- structs usually used for data only structures, classes for classes that have procedures and member functions
- use private because in large projects important that values not be modified in an unexpected way from the POV of the object
- advantage of class declare several diff objects from it, each object of Rect has its own variable x, y AND its own functions
- concept of OO programming: data and functions are properties of the object instead of the usual view of objects as function parameters in structured programming
- Difference between
assignment operator and copy constructor - -assignment operator =
assigning a variable to a value - copy constructor
- constructor with only one parameter of its same type that assigns to every nonstatic class member variable of the object a copy of the passed object
- copy assignment operator must correctly deal with a well constructed object - but copy constructor initializes uninitialized memory
- copy constructor takes care of initialization by an object of the same type x
- for a class for which the copy assignment and copy constructor not explicitly declared missing operation will be generated by the compiler. Copy operations are not inherited - copy of a class object is a copy of each member
- memberwise assignment: each member of the right hand object is assigned to the corresponding member of the left hand object
- if a class needs a copy constructor it will also need an assignment operator
- copy constructor creates a new object, assignment operator has to deal w/ existing data in the object
- assignment is like deconstruction followed by construction
- assignment operator assigns a value to a already existing object
- copy constructor creates a new object by copying an existing one
- copy constructor initializes a freshly created object using data from an existing one. It must allocate memory if necessary then copy the data
- the assignment operator makes an already existing object into a copy of an existing one.
- copy constructor always creates a new object, assignment never does
- Difference
between overloading and overriding?
- Overload - two functions that appear in the same scope are overloaded if they have the same name but have different parameter list
- main() cannot be overloaded
- notational convenience - compiler invokes the functions that is the best match on the args – found by finding the best match between the type of arg expr and parameter
- if declare a function locally, that function hides rather than overload the same function declared in an outer scope
- Overriding - the ability of the inherited class rewriting the virtual method of a base class - a method which completely replaces base class FUNCTIONALITY in subclass
- the overriding method in the subclass must have exactly the same signature as the function of the base class it is replacing - replacement of a method in a child class
- writing a different body in a derived class for a function defined in a base class, ONLY if the function in the base class is virtual and ONLY if the function in the derived class has the same signature
- all functions in the derived class hide the base class functions with the same name except in the case of a virtual functions which override the base class functions with the same signature
- Virtual
- single most important feature of C++ BUT virtual costs
- allows derived classes to replace the implementation provided by the base class
- without virtual functions C++ wouldnt be object oriented
- Programming with classes but w/o dynamic binding == object based not OO
- dynamic binding can improve reuse by letting old code call new code
- functions defined as virtual are ones that the base expects its derived classes to redefine
- virtual precedes return type of a function
- virtual keyword appears only on the member function declaration inside the class
- virtual keyword may not be used on a function definition that appears outside the class body
- default member functions are nonvirtual
- Dynamic
Binding
- delaying until runtime the selection of which function to run
- refers to the runtime choice of which virtual function to run based on the underlying type of the object to which a reference or a pointer is based
- applies only to functions declared as virtual when called thru reference or ptr
- in C++ dynamic binding happens when a virtual function is called through a reference (|| ptr) to a base class. The face that ref or ptr might refer to either a base or a derived class object is the key to dynamic binding. Calls to virtual functions made thru a reference or ptr are resolved at run time: the function that is called is the one defined by the actual type of the object to which the reference or pointer refers
- Explain
the need for a virtual destructor
- destructor for the base parts are invoked automatically
- we might delete a ptr to the base type that actually points to a derived object
- if we delete a ptr to base then the base class destructor is run and the members of the base class are cleared up. If the objectis a derived type then the behavior is undefined
- to ensure that the proper destructor is run the destructor must be virtual in the base class
- virtual destructor needed if base pointer that points to a derived object is ever deleted (even if it doesnt do any work)
- Rule
of 3
- if a class needs a destructor, it will also need an assignment operator and copy constructor
- compiler always synthesizes a destructor for us
- destroys each nonstatic member in the reverse order from that in which the object was created
- it destroys the members in reverse order from which they are declared in the class1. if someone will derive from your class2. and if someone will say new derived where derived is derived from your class3. and if someone will say delete p, where the actual objects type is derived but the pointer ps type is your class
- make destructor virtual if your class has any virtual functions
- Why do you need a virtual destructor when someone says delete using a Base ptr thats pointing @ a derived object? - when you say delete p and the class of p has a virtual destructor the destructor that gets invoked is the one assoc with the type of the object*p not necessarily the one assoc with the type of the pointer == GOOD
- Different
types of polymorphism
- types related by inheritance as polymorphic types because we can use many forms of a derived or base type interchangeably
- only applies to ref or ptr to types related by inheritance.
- Inheritance - lets us define classes that model relationships among types, sharing what is common and specializing only that which is inherently different
- derived
classes
- can use w/o change those operations that dont depend on the specifics of the derived type
- redefine those member functions that do depend on its type
- derived class may define additional members beyond those it inherits from its base class.
- Dynamic Binding - lets us write programs that use objects of any type in an inheritance hierarchy w/o caring about the objects specific types
- happens when a virtual function is called through a reference || ptr to a base class
- The fact that a reference or ptr might refer to either a base or derived class object is the key to dynamic binding
- calls to virtual functions made though a reference/ptr resolved @ runtime
- the function that is called is the one defined by the actual type of the object to which ref/ptr refers
- How to implement virtual functions in C - keep function pointers in function and use those function ptrs to perform the operation
- What
are the different type of Storage classes?
- automatic storage: stack memory - static storage: for namespace scope objects and local statics
- free store: or heap for dynamically allocated objects == design patterns
- What
is a namespace?
- every name defined in a global scope must be unique w/in that scope
- name collisions: same name used in our own code or code supplied to us by indie producers == namespace pollution
- name clashing - namespace provides controlled mechanism for preventing name collisions
- allows us to group a set of global classes/obj/funcs
- in order to access variables from outside namespace have to use scope :: operator
- using namespace serves to assoc the present nesting level with a certain namespace so that objectand funcs of that namespace can be accessible directly as if they were defined in the global scope
- Types of STL containers - containers are objects that store other objects and that has methods for accessing its elements - has iterator - vector
- Difference between vector and array - -array: data structure used dto store a group of objects of the same type sequentially in memory - vector: container class from STL - holds objects of various types - resize, shrinks grows as elements added - bugs such as accessing out of bounds of an array are avoided
- Write a program that will delete itself after execution. Int main(int argc, char **argv) { remove(argv[0]);return 0;}
- What are inline functions?
- treated like macro definitions by C++ compiler
- meant to be used if there’s a need to repetitively execute a small block if code which is smaller
- always evaluates every argument once
- defined in header file
- avoids function call overload because calling a function is slower than evaluating the equivalent expression
- it’s a request to the compiler, the compiler can ignore the request
- What is strstream? defines classes that support iostreams, array of char obj
- Passing by ptr/val/refArg?
- passing by val/refvoid c::f(int arg) – by value arg is a new int existing only in function. Its initial value is copied from i. modifications to arg wont affect the I in the main function
- void c::f(const int arg) – by value (i.e. copied) the const keyword means that arg cant be changed, but even if it could it wouldnt affect the I in the main function
- void c::f(int& arg) - -by reference, arg is an alias for I. no copying is done. More efficient than methods that use copy. Change in arg == change in I in the calling function
- void c::f(const int& arg) - -by reference, int provided in main call cant be changed, read only. Combines safety with efficacy.
- void c::f(const int& arg) const – like previous but final const that in addition the function f cant change member variables of cArg passing using pointers
- void c::f(int *arg) – by reference changing *arg will change the I in the calling function
- void c::f(const int *arg) – by reference but this time the I int in the main function cant be changed – read only
- void c::f(int * const arg) – by reference the pointer arg cant be changed but what it points to (namely I of the calling function) can
- void c::f(const int * const arg) by reference the pointer arg cant be changed neither can what it points to
- Mutable keyword?
- keyword is the key to make exceptions to const
- mutable data member is allowed to change during a const member function
- mutable data member is never const even when it is a member of a const object
- a const member function may change a mutable member
- Something you can do in C but not in C++? C++ applications generally slower at runtime and compilation - input/output
- Difference
between calloc and malloc?
- malloc: allocate s bytes
- calloc: allocate n times s bytes initialized to 0
- What will happen if I allocate memory using new & free memory using free? WRONG
- Difference between printf and sprintf?
- sprintf: a function that puts together a string, output goes to an array of char instead of stdout
- printf: prints to stdout
- map
in STL?
- used to store key - value pairs, value retrieved using the key
- store data indexed by keys of any type desire instead of integers as with arrays
- maps are fast 0(log(n)) insertion and lookup time
- std::map<key_type, data_type>EX:Std::map<string, char> grade_list //grade_list[â€Å"johnâ€Â] = b
- When
will we use multiple inheritance?
- use it judiciously class
- when MI enters the design scope it becomes possible to inherit the same name (function/typedef) from more than one base class == ambiguity
- C++ first identifies the function thats the best match for the call
- C++ resolves calls to overload before accessibility, therefore the accessibility of Elec_Gadget() checkout is never evaluated because both are good matches == ERROR
- resolve ambiguity mp.Borrowable_Item::checkOut(); mp.Elec_Gadget::checkOut(); //error because trying to access private
- deadly MI diamond: anytime you have an inheritance hierarchy w/ more than one path between a base class and a derived classEX:FileInput File Output FileIOFile//File and IOFile both have paths through InputFile and OutputFile
- Multithreading - C++ does not have a notion of multithreading, no notion of concurrency
- Why is the pre-increment operator faster than the post-increment operator? pre is more efficient that post because for post the object must increment itself and then return a temporary containing its old value. True for even built in types
- What is a hash and what would you use it for?
- What is a dot product and what is a cross product - what would you use them for?
- What is 2 ^ 101?
Monday, March 22, 2010
C++ notes for discussion
-
The following article discusses the WPF command binding feature with relation to Mouse clicks. One of WPF powerful features is the bindin...
-
SQL Server has never been short of ways to read from and write to files and it is always better to use the standard techniques provided b...
-
In this article we will look at the basics of Angular.Js. This is the first part of an article series. The main objective of this series i...