Wednesday, March 13, 2013

V table compiler option to see calss heirarchy

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)

See Vtable compiler option

g++ -fdump-class-hierarchy

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]

Wednesday, September 14, 2011

C++Object Oriented Questions n Answers

  1. 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;
    }
    };
    
  2. 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
  3. 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.
  4. 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.
  5. 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.
  6. What is the use of ‘using’ declaration.
    A using declaration makes it possible to use a name from a namespace without the scope operator.
  7. 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.
  8. 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.
  9. 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).
  10. 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.
    int *i=0x400  // i points to address 400
    *i=0;        //set the value of memory location pointed by i.
    
    Incomplete types are otherwise called uninitialized pointers.
  11. 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:
    class 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;"> 
    In the above example when PrintVal() function is
    called it is called by the pointer that has been freed by the
    destructor in SomeFunc.
  12. Differentiate between the message and method.
    Message:
    • Objects communicate by sending messages to each other.
    • A message is sent to invoke a method.
    Method
    • Provides response to a message.
    • It is an implementation of an operation.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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.
  18. 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.
  19. What are proxy objects? Objects that stand for other objects are called proxy objects or surrogates.
    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;
    };
    
    The following then becomes legal:
    Array2Ddata(10,20);
    cout<
    Here data[3] yields an Array1D object
    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.
  20. Name some pure object oriented languages. Smalltalk, Java, Eiffel, Sather.
  21. Name the operators that cannot be overloaded. sizeof, ., .*, .->, ::, ?: Salam in the comments notes that -> can be overloaded.
  22. 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.
    A node class is a class that has added new services or functionality beyond the services inherited from its base class.
  23. 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.
  24. 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.

C++ Questions n Answers

  1. What is the output of printf(“%d”)?
    1. %d helps to read integer data type of a given variable
    2. when we write (“%d”, X) compiler will print the value of x assumed in the main
    3. but nothing after (“%d”) so the output will be garbage
    4. printf is an overload function doesnt check consistency of the arg list – segmentation fault
  2. 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()
    1. pointer var will still be valid
    2. object created by new exists until explicitly destroyed by delete
    3. space it occupied can be reused by new
    4. delete may only be applied to a pointer by new or zero, applying delete to zero = no FX
    5. delete = delete objects
    6. delete[] – delete array
    7. delete operator destroys the object created with new by deallocating the memory assoc. with the object
    8. if a destructor has been defined fir a class delete invokes that desructor
  3. Difference between C structure and C++ structure - C++ places greater emphasis on type checking, compiler can diagnose every diff between C and C++
    1. structures are a way of storing many different values in variables of potentially diff types under under the same name
    2. classes and structures make program modular, easier to modify make things compact
    3. useful when a lot of data needs to be grouped together
    4. struct Tag {…}struct example {Int x;}example ex; ex.x = 33; //accessing variable of structure
    5. members of a struct in C are by default public, in C++ private
    6. 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
    7. pointers can point to struct:
    8. C++ can use class instead of struct (almost the same thing) - difference: C++ classes can include functions as members
    9. 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
    10. structs usually used for data only structures, classes for classes that have procedures and member functions
    11. use private because in large projects important that values not be modified in an unexpected way from the POV of the object
    12. advantage of class declare several diff objects from it, each object of Rect has its own variable x, y AND its own functions
    13. 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
  4. Difference between assignment operator and copy constructor - -assignment operator = assigning a variable to a value - copy constructor
    1. 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
    2. copy assignment operator must correctly deal with a well constructed object - but copy constructor initializes uninitialized memory
    3. copy constructor takes care of initialization by an object of the same type x
    4. 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
    5. memberwise assignment: each member of the right hand object is assigned to the corresponding member of the left hand object
    6. if a class needs a copy constructor it will also need an assignment operator
    7. copy constructor creates a new object, assignment operator has to deal w/ existing data in the object
    8. assignment is like deconstruction followed by construction
    9. assignment operator assigns a value to a already existing object
    10. copy constructor creates a new object by copying an existing one
    11. copy constructor initializes a freshly created object using data from an existing one. It must allocate memory if necessary then copy the data
    12. the assignment operator makes an already existing object into a copy of an existing one.
    13. copy constructor always creates a new object, assignment never does
  5. Difference between overloading and overriding?
    1. Overload - two functions that appear in the same scope are overloaded if they have the same name but have different parameter list
    2. main() cannot be overloaded
    3. 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
    4. if declare a function locally, that function hides rather than overload the same function declared in an outer scope
    5. 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
    6. 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
    7. 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
    8. 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
  6. Virtual
    1. single most important feature of C++ BUT virtual costs
    2. allows derived classes to replace the implementation provided by the base class
    3. without virtual functions C++ wouldnt be object oriented
    4. Programming with classes but w/o dynamic binding == object based not OO
    5. dynamic binding can improve reuse by letting old code call new code
    6. functions defined as virtual are ones that the base expects its derived classes to redefine
    7. virtual precedes return type of a function
    8. virtual keyword appears only on the member function declaration inside the class
    9. virtual keyword may not be used on a function definition that appears outside the class body
    10. default member functions are nonvirtual
  7. Dynamic Binding
    1. delaying until runtime the selection of which function to run
    2. 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
    3. applies only to functions declared as virtual when called thru reference or ptr
    4. 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
  8. Explain the need for a virtual destructor
    1. destructor for the base parts are invoked automatically
    2. we might delete a ptr to the base type that actually points to a derived object
    3. 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
    4. to ensure that the proper destructor is run the destructor must be virtual in the base class
    5. virtual destructor needed if base pointer that points to a derived object is ever deleted (even if it doesnt do any work)
  9. Rule of 3
    1. if a class needs a destructor, it will also need an assignment operator and copy constructor
    2. compiler always synthesizes a destructor for us
    3. destroys each nonstatic member in the reverse order from that in which the object was created
    4. 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
    5. make destructor virtual if your class has any virtual functions
  10. 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
  11. Different types of polymorphism
    1. types related by inheritance as polymorphic types because we can use many forms of a derived or base type interchangeably
    2. only applies to ref or ptr to types related by inheritance.
    3. Inheritance - lets us define classes that model relationships among types, sharing what is common and specializing only that which is inherently different
    4. derived classes
      1. can use w/o change those operations that dont depend on the specifics of the derived type
      2. redefine those member functions that do depend on its type
      3. derived class may define additional members beyond those it inherits from its base class.
    5. Dynamic Binding - lets us write programs that use objects of any type in an inheritance hierarchy w/o caring about the objects specific types
    6. happens when a virtual function is called through a reference || ptr to a base class
    7. The fact that a reference or ptr might refer to either a base or derived class object is the key to dynamic binding
    8. calls to virtual functions made though a reference/ptr resolved @ runtime
    9. the function that is called is the one defined by the actual type of the object to which ref/ptr refers
  12. How to implement virtual functions in C - keep function pointers in function and use those function ptrs to perform the operation
  13. What are the different type of Storage classes?
    1. automatic storage: stack memory - static storage: for namespace scope objects and local statics
    2. free store: or heap for dynamically allocated objects == design patterns
  14. What is a namespace?
    1. every name defined in a global scope must be unique w/in that scope
    2. name collisions: same name used in our own code or code supplied to us by indie producers == namespace pollution
    3. name clashing - namespace provides controlled mechanism for preventing name collisions
    4. allows us to group a set of global classes/obj/funcs
    5. in order to access variables from outside namespace have to use scope :: operator
    6. 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
  15. Types of STL containers - containers are objects that store other objects and that has methods for accessing its elements - has iterator - vector
  16. 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
  17. Write a program that will delete itself after execution. Int main(int argc, char **argv) { remove(argv[0]);return 0;}
  18. What are inline functions?
    1. treated like macro definitions by C++ compiler
    2. meant to be used if there’s a need to repetitively execute a small block if code which is smaller
    3. always evaluates every argument once
    4. defined in header file
    5. avoids function call overload because calling a function is slower than evaluating the equivalent expression
    6. it’s a request to the compiler, the compiler can ignore the request
  19. What is strstream? defines classes that support iostreams, array of char obj
  20. Passing by ptr/val/refArg?
    1. 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
    2. 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
    3. 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
    4. void c::f(const int& arg) - -by reference, int provided in main call cant be changed, read only. Combines safety with efficacy.
    5. 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
    6. void c::f(int *arg) – by reference changing *arg will change the I in the calling function
    7. void c::f(const int *arg) – by reference but this time the I int in the main function cant be changed – read only
    8. 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
    9. void c::f(const int * const arg) by reference the pointer arg cant be changed neither can what it points to
  21. Mutable keyword?
    1. keyword is the key to make exceptions to const
    2. mutable data member is allowed to change during a const member function
    3. mutable data member is never const even when it is a member of a const object
    4. a const member function may change a mutable member
  22. Something you can do in C but not in C++? C++ applications generally slower at runtime and compilation - input/output
  23. Difference between calloc and malloc?
    1. malloc: allocate s bytes
    2. calloc: allocate n times s bytes initialized to 0
  24. What will happen if I allocate memory using new & free memory using free? WRONG
  25. map in STL?
    1. used to store key - value pairs, value retrieved using the key
    2. store data indexed by keys of any type desire instead of integers as with arrays
    3. maps are fast 0(log(n)) insertion and lookup time
    4. std::mapEX:Std::map grade_list //grade_list[“john”] = b
  26. When will we use multiple inheritance?
    1. use it judiciously class
    2. when MI enters the design scope it becomes possible to inherit the same name (function/typedef) from more than one base class == ambiguity
    3. C++ first identifies the function thats the best match for the call
    4. C++ resolves calls to overload before accessibility, therefore the accessibility of Elec_Gadget() checkout is never evaluated because both are good matches == ERROR
    5. resolve ambiguity mp.Borrowable_Item::checkOut(); mp.Elec_Gadget::checkOut(); //error because trying to access private
    6. 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
  27. Multithreading - C++ does not have a notion of multithreading, no notion of concurrency
  28. 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

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.

#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 f(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 for f(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);
 }

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  
unexpected_handler old_hand  = set_unexpected( newfunction);
 
void newfunction( ) 
{
   cout << "Hi" << endl;
   terminate( );
}
 

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

Saturday, May 8, 2010

Exception Handling

Q How to catch all type of Exception ?
Ans Three dots try { } catch(...)
three dots is called   Ellipsis

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 
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

Followers