Use g++ -fdump-class-hierarchy
Vtable for base
base::_ZTV4base: 3u entries
0 (int (*)(...))0
4 (int (*)(...))(& _ZTI4base)
8 base::printmyname
Class base
size=8 align=4
base size=8 base align=4
base (0xb6dd9c30) 0
vptr=((& base::_ZTV4base) + 8u)
Vtable for derive1
derive1::_ZTV7derive1: 3u entries
0 (int (*)(...))0
4 (int (*)(...))(& _ZTI7derive1)
8 derive1::printmyname
Class derive1
size=12 align=4
base size=12 base align=4
derive1 (0xb6d6ca80) 0
vptr=((& derive1::_ZTV7derive1) + 8u)
base (0xb6dd9c6c) 0
primary-for derive1 (0xb6d6ca80)
CPP Learnings
This blog is created to improve CPP and OOPS concept . It include OOPS concept , CPP FAQ , CPP Interview questions and many helpful material to improve CPP
Wednesday, March 13, 2013
Saturday, September 24, 2011
Constructor , Copy Constructor and Synthesized Default Constructor
Copy Constructor :
Get invoked when :
1 Object is created and initialized at same time .
2.When function returns object .
3.A Value parameter is initialized from its corresponding argument in function call.
in pass by value .
cc is called in this cases
student S2(S1)
student S2 =S1
copy constructor will not invoked in these cases :
S2 = S1 here bitwise copy will happen Assignment operator must be overloaded for deep
copying scenario.
Student S1 ;
When is a Constructor Synthesized ?
1.Class has member object of another class which has default Constructor. [to invoke member objs ctor]
2.Base class with default Ctor [to invoke the default ctor of each of its immediate base classes in order of their declarations]
3.If class or any of its base class has virtual function. [to initialize VPTR -->VTBL]
4. Class with virtual Base Class.[to initialize pointer to virtual base class]
Get invoked when :
1 Object is created and initialized at same time .
2.When function returns object .
3.A Value parameter is initialized from its corresponding argument in function call.
in pass by value .
cc is called in this cases
student S2(S1)
student S2 =S1
copy constructor will not invoked in these cases :
S2 = S1 here bitwise copy will happen Assignment operator must be overloaded for deep
copying scenario.
Student S1 ;
When is a Constructor Synthesized ?
1.Class has member object of another class which has default Constructor. [to invoke member objs ctor]
2.Base class with default Ctor [to invoke the default ctor of each of its immediate base classes in order of their declarations]
3.If class or any of its base class has virtual function. [to initialize VPTR -->VTBL]
4. Class with virtual Base Class.[to initialize pointer to virtual base class]
Labels:
Constructor,
Copy Constructor
Wednesday, September 14, 2011
C++Object Oriented Questions n Answers
- What is a modifier? A modifier, also called a modifying function is a member function that
changes the value of at least one data member. In other words, an
operation that modifies the state of an object. Modifiers are also
known as ‘mutators’. Example: The function mod is a modifier in the
following code snippet:class test { int x,y; public: test() { x=0; y=0; } void mod() { x=10; y=15; } };
- What is an accessor? An accessor is a class operation that
does not modify the state of an object. The accessor functions need to
be declared as const operations - Differentiate between a template class and class template.
Template class: A generic definition or a parameterized class not
instantiated until the client provides the needed information. It’s
jargon for plain templates. Class template: A class template specifies
how individual classes can be constructed much like the way a class
specifies how individual objects can be constructed. It’s jargon for
plain classes. - When does a name clash occur? A name clash occurs
when a name is defined in more than one place. For example., two
different class libraries could give two different classes the same
name. If you try to use many class libraries at the same time, there is
a fair chance that you will be unable to compile or link the program
because of name clashes. - Define namespace. It is a feature in C++ to
minimize name collisions in the global name space. This namespace
keyword assigns a distinct name to a library that allows other
libraries to use the same identifier names without creating any name
collisions. Furthermore, the compiler uses the namespace signature for
differentiating the definitions. - What is the use of ‘using’ declaration.
A using declaration makes it possible to use a name from a namespace without the scope operator. - What is an Iterator class? A class that is used to
traverse through the objects maintained by a container class. There are
five categories of iterators: input iterators, output iterators,
forward iterators, bidirectional iterators, random access. An iterator
is an entity that gives access to the contents of a container object
without violating encapsulation constraints. Access to the contents is
granted on a one-at-a-time basis in order. The order can be storage
order (as in lists and queues) or some arbitrary order (as in array
indices) or according to some ordering relation (as in an ordered
binary tree). The iterator is a construct, which provides an interface
that, when called, yields either the next element in the container, or
some value denoting the fact that there are no more elements to
examine. Iterators hide the details of access to and update of the
elements of a container class.
The simplest and safest iterators are those that permit read-only access to the contents of a container class. - List out some of the OODBMS available. GEMSTONE/OPAL
of Gemstone systems, ONTOS of Ontos, Objectivity of Objectivity Inc,
Versant of Versant object technology, Object store of Object Design,
ARDENT of ARDENT software, POET of POET software. - List out some of the object-oriented methodologies. Object Oriented Development (OOD) (Booch 1991,1994), Object
Oriented Analysis and Design (OOA/D) (Coad and Yourdon 1991), Object
Modelling Techniques (OMT) (Rumbaugh 1991), Object Oriented Software
Engineering (Objectory) (Jacobson 1992), Object Oriented Analysis (OOA)
(Shlaer and Mellor 1992), The Fusion Method (Coleman 1991). - What is an incomplete type? Incomplete types
refers to pointers in which there is non availability of the
implementation of the referenced location or it points to some location
whose value is not available for modification.
Incomplete types are otherwise called uninitialized pointers.int *i=0x400 // i points to address 400 *i=0; //set the value of memory location pointed by i.
- What is a dangling pointer?
A dangling pointer arises when you use the address of an object after
its lifetime is over. This may occur in situations like returning
addresses of the automatic variables from a function or using the
address of the memory block after it is freed. The following
code snippet shows this:
In the above example when PrintVal() function isclass Sample { public: int *ptr; Sample(int i) { ptr = new int(i); } ~Sample() { delete ptr; } void PrintVal() { cout << "The value is " << *ptr; } }; void SomeFunc(Sample x) { cout << "Say i am in someFunc " << s1 =" 10;">
called it is called by the pointer that has been freed by the
destructor in SomeFunc. - Differentiate between the message and method.
Message:- Objects communicate by sending messages to each other.
- A message is sent to invoke a method.
- Provides response to a message.
- It is an implementation of an operation.
- What is an adaptor class or Wrapper class?
A class that has no functionality of its own. Its member functions hide
the use of a third party software component or an object with the
non-compatible interface or a non-object-oriented implementation. - What is a Null object? It is an object of some
class whose purpose is to indicate that a real object of that class
does not exist. One common use for a null object is a return value from
a member function that is supposed to return an object with some
specified properties but cannot find such an object. - What is class invariant? A class invariant is a
condition that defines all valid states for an object. It is a logical
condition to ensure the correct working of a class. Class invariants
must hold when an object is created, and they must be preserved under
all operations of the class. In particular all class invariants are
both preconditions and post-conditions for all operations or member
functions of the class. - What do you mean by Stack unwinding? It is a
process during exception handling when the destructor is called for all
local objects between the place where the exception was thrown and
where it is caught. - Define precondition and post-condition to a member function.
Precondition: A precondition is a condition that must be true on entry
to a member function. A class is used correctly if preconditions are
never false. An operation is not responsible for doing anything
sensible if its precondition fails to hold. For example, the interface
invariants of stack class say nothing about pushing yet another element
on a stack that is already full. We say that isful() is a precondition
of the push operation. Post-condition: A post-condition is a condition
that must be true on exit from a member function if the precondition
was valid on entry to that function. A class is implemented correctly
if post-conditions are never false. For example, after pushing an
element on the stack, we know that isempty() must necessarily hold.
This is a post-condition of the push operation. - What are the conditions that have to be met for a condition to be an invariant of the class?
- The condition should hold at the end of every constructor.
- The condition should hold at the end of every mutator (non-const) operation.
- What are proxy objects? Objects that stand for other objects are called proxy objects or surrogates.
The following then becomes legal:template class Array2D { public: class Array1D { public: T& operator[] (int index); const T& operator[] (int index)const; }; Array1D operator[] (int index); const Array1D operator[] (int index) const; };
Here data[3] yields an Array1D objectArray2Ddata(10,20); cout<
and the operator [] invocation on that object yields the float in
position(3,6) of the original two dimensional array. Clients of the
Array2D class need not be aware of the presence of the Array1D class.
Objects of this latter class stand for one-dimensional array objects
that, conceptually, do not exist for clients of Array2D. Such clients
program as if they were using real, live, two-dimensional arrays. Each
Array1D object stands for a one-dimensional array that is absent from a
conceptual model used by the clients of Array2D. In the above example,
Array1D is a proxy class. Its instances stand for one-dimensional
arrays that, conceptually, do not exist. - Name some pure object oriented languages. Smalltalk, Java, Eiffel, Sather.
- Name the operators that cannot be overloaded. sizeof, ., .*, .->, ::, ?: Salam in the comments notes that -> can be overloaded.
- What is a node class? A node class is a class that,
- relies on the base class for services and implementation,
- provides a wider interface to the users than its base class,
- relies primarily on virtual functions in its public interface
- depends on all its direct and indirect base class
- can be understood only in the context of the base class
- can be used as base for further derivation
- can be used to create objects.
- What is an orthogonal base class?
If two base classes have no overlapping methods or data they are said
to be independent of, or orthogonal to each other. Orthogonal in the
sense means that two classes operate in different dimensions and do not
interfere with each other in any way. The same derived class may
inherit such classes with no difficulty. - What is a container class? What are the types of container classes? A container class is a class that is used to hold objects in memory or
external storage. A container class acts as a generic holder. A
container class has a predefined behavior and a well-known interface. A
container class is a supporting class whose purpose is to hide the
topology used for maintaining the list of objects in memory. When a
container class contains a group of mixed objects, the container is
called a heterogeneous container; when the container is holding a group
of objects that are all the same, the container is called a homogeneous
container.
Labels:
FAQ
C++ Questions n Answers
- 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
- 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::mapEX:Std::map 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
Labels:
FAQ
Tuesday, August 24, 2010
C in C++ Code and C++ code in C
extern "C" is understandable by only C++ compiler thats why we generaly wrap it in # if defs . When same code can be compiled by c compiler also
only cpp compiler has defined cpluscplus.
#ifdef __cplusplus
extern "C" {
#endif
In cpp code if we want a function that will be callable from C program.We need declaration like this
cpp file.
A function declared as extern "C" uses the function name as symbol name, just as a C function. For that reason, only non-member functions can be declared as extern "C", and they cannot be overloaded.
C++ compiler uses a technique termed name mangling which incorporates the function name with its signature (list of arguments) in order to create a unique name for it, even in case of overloading (this technique is used both for external function and class member functions).
In order to enforce the compiler to avoid name mangling, a global function has to be declared as extern "C":
extern "C" void f(int); //now the generated name is identical to the one given by the programmer.
How to include non standard C header file in C++ code?
//C++ code
extern "C" {
// Get declaration forf(int i, char c)
#include "my-C-code.h"
}
int main()
{
f(7, 'a');
...
}
To make it easier its better to change header file itself .
at top putting
#ifdef __cplusplus
extern "C" {
#endif
At end put
#ifdef __cplusplus
}
#endif
Now it .h can be included in cPP simply
// Get declaration forf(int i, char c, float x)
#include "my-C-code.h"
int main()
{
f(7, 'x');
...
}
--------------
if we dont want to include whole file individual function can be declared
extern "C" void f(int i, char c);
Or a group can be :
extern "C" {
void f(int i, char c);
int f2(char* s, char const* s2);
double f3(double a, double b);
}
only cpp compiler has defined cpluscplus.
#ifdef __cplusplus
extern "C" {
#endif
In cpp code if we want a function that will be callable from C program.We need declaration like this
cpp file.
#include
extern "C" void hello() {
std::cout << "hello" << '\n';
}
A function declared as extern "C" uses the function name as symbol name, just as a C function. For that reason, only non-member functions can be declared as extern "C", and they cannot be overloaded.
C++ compiler uses a technique termed name mangling which incorporates the function name with its signature (list of arguments) in order to create a unique name for it, even in case of overloading (this technique is used both for external function and class member functions).
In order to enforce the compiler to avoid name mangling, a global function has to be declared as extern "C":
extern "C" void f(int); //now the generated name is identical to the one given by the programmer.
How to include non standard C header file in C++ code?
//C++ code
extern "C" {
// Get declaration for
#include "my-C-code.h"
}
int main()
{
f(7, 'a');
...
}
To make it easier its better to change header file itself .
at top putting
#ifdef __cplusplus
extern "C" {
#endif
At end put
#ifdef __cplusplus
}
#endif
Now it .h can be included in cPP simply
// Get declaration for
#include "my-C-code.h"
int main()
{
f(7, 'x');
...
}
--------------
if we dont want to include whole file individual function can be declared
extern "C" void f(int i, char c);
Or a group can be :
extern "C" {
void f(int i, char c);
int f2(char* s, char const* s2);
double f3(double a, double b);
}
Tuesday, May 11, 2010
Unexpected Exception
How to specify Exception?
func() // this can throw any Excpeption
func() throw() // this Will NOT throw any Excpeption
func() throw (bad_alloc , X ) // this can throw only specified Excpeption
unexpected() is called when function throws exception other than specified
It uses _unexpected_handler which can be changed
func() // this can throw any Excpeption
func() throw() // this Will NOT throw any Excpeption
func() throw (bad_alloc , X ) // this can throw only specified Excpeption
unexpected() is called when function throws exception other than specified
It uses _unexpected_handler which can be changed
unexpected_handler old_hand = set_unexpected( newfunction);
void newfunction( ) { cout << "Hi" << endl; terminate( ); }
Labels:
Exception Handling
Sunday, May 9, 2010
Auotmatic Type Conversion and use of Explicit Keyword
1. By Constructor Conversion :
See this situation .
Output :
Constructor B called
Hi inside Function
--------------------------------------------------------------------------------
Preventing constructor conversion.
This Behaviour of automatic calling of constructor . can be stopped if constructor is explicit.
Explicit Constructor: Constructor with explicit keyword.It prevents compliler from performing implicit (Unexpected) type conversions.
After this func (a); will not get compiled .
Output:Compliation Fails
auotTypeConversion.cpp: In function `int main()':
auotTypeConversion.cpp:18: error: conversion from `A' to non-scalar type `B' requested
2. Operator Conversion :
OUTPUT:
inside conversion operator B--> A
inside A constructor i=10
Function call
See this situation .
Output :
Constructor B called
Hi inside Function
--------------------------------------------------------------------------------
Preventing constructor conversion.
This Behaviour of automatic calling of constructor . can be stopped if constructor is explicit.
Explicit Constructor: Constructor with explicit keyword.It prevents compliler from performing implicit (Unexpected) type conversions.
After this func (a); will not get compiled .
Output:Compliation Fails
auotTypeConversion.cpp: In function `int main()':
auotTypeConversion.cpp:18: error: conversion from `A' to non-scalar type `B' requested
2. Operator Conversion :
OUTPUT:
inside conversion operator B--> A
inside A constructor i=10
Function call
Labels:
Explicit,
Type Conversion
Saturday, May 8, 2010
Exception Handling
Q How to catch all type of Exception ?
Ans Three dots try { } catch(...)
three dots is called Ellipsis
Ans Three dots try { } catch(...)
three dots is called Ellipsis
Labels:
Exception Handling
Friday, May 7, 2010
When to return const refrence ?
a)When do we return by refrence?
Ans:. it avoids copying . But never return reference of local object .
So that functions can be l-values
We do this when we want to modify lvalue . we do this in operator overlaoding of " =" to support a=b=c chaining
b) Returning just const
As const return can be assigned to nonconst variable and changed .
But if function is used in expression then temporary return as it is const will be prohibited .
struct foo
{
void bar() {}
void barfoo() const {}
};
foo foobar1() {return foo();}
const foo foobar2() {return foo();}
int main()
{
foobar1().barfoo(); //perfectly legal, calling const member function of non-const object
foobar1().bar(); //perfectly legal, calling non-const member function of non-const object
foobar2().barfoo(); // perfectly legal, calling const member function of const object
foobar2().bar(); // this willl not compile
}
In operator overloading we use it often to make sure
(a+b)=c // this kind of things will not get compile
We make sure (a+b).func() is allowed only if func()is const function .
this is called const correectness
c)When to return const refrence
This make lot of sense .
http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
Ans:. it avoids copying . But never return reference of local object .
So that functions can be l-values
We do this when we want to modify lvalue . we do this in operator overlaoding of " =" to support a=b=c chaining
MyClass & operator=(const MyClass &rhs);
MyClass & operator+=(const MyClass &rhs)
b) Returning just const
As const return can be assigned to nonconst variable and changed .
But if function is used in expression then temporary return as it is const will be prohibited .
struct foo
{
void bar() {}
void barfoo() const {}
};
foo foobar1() {return foo();}
const foo foobar2() {return foo();}
int main()
{
foobar1().barfoo(); //perfectly legal, calling const member function of non-const object
foobar1().bar(); //perfectly legal, calling non-const member function of non-const object
foobar2().barfoo(); // perfectly legal, calling const member function of const object
foobar2().bar(); // this willl not compile
}
In operator overloading we use it often to make sure
const MyClass MyClass::operator+(const MyClass &other) const
(a+b)=c // this kind of things will not get compile
We make sure (a+b).func() is allowed only if func()is const function .
this is called const correectness
c)When to return const refrence
This make lot of sense .
http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
Subscribe to:
Posts (Atom)