Thursday, 3 May 2018

FAQ CPP

virtual functions?
 Virtual functions allow the programmer to redefine in each derived class functions from the base class with altered behavior so that you can call the right function for the right object


class Shape  
{
public:
    ...
    //a shape can be drawn in many ways
    virtual void draw(){ };
};
class Square : public Rectangle
{
public:
    ...
    void draw() { };
};
Shape* theShape = new Square();
// with the help of virtual functions
// a Square will be drawn and not
// a Rectangle or any other Shape
theShape->draw();
The redefinition of a virtual function in a derived class is called overriding.


Through virtual functions C++ achieves what is called late binding (dynamic binding or runtime binding), that is actually connecting a function call to a function body at runtime .


virtual destructor and when would you use one?


declaring the destructor virtual you ensure it is placed in the VTABLE of the class and it will be called at proper times


make a class’ destructor virtual to ensure proper clean-up when the class is supposed to be subclassed to form a hierarchy and you want to delete a derived object thorough a pointer to it (the base class).
Base* b = new Derived(theName);

    // do some computations and then delete the
    // pointer
    delete b;
when you want to delete a derived class object through a base class pointer and the destructor of the base class is not virtual the result is undefined.
What is the most often behavior in such situations is that the derived class’ destructor is never called and parts of your derived object are left undestroyed.


That makes sense (declaring the destructor virtual) only if your class is supposed to be part of a hierarchy as a base class, otherwise you’ll just waste memory with the class’vtable generated only for the destructor. So declare a virtual destructor in a class “if and only if that class is part of a class hierarchy, containing at least one virtual function. 


Abstract Class
obtain an abstract class in C++ by declaring at least one pure virtual function in that class. A virtual function is transformed in a pure virtual with the help of the initializer “= 0″. A pure virtual function does not need a definition. An abstract class cannot be instantiated but only used as a base in a hierarchy
class MySillyAbstract
{
public:
    // just declared not defined
    virtual void beSilly() = 0;
};












u can obtain an “interface” in C++ by declaring an abstract class with all the functions pure virtual functions and public and no member variables – only behavior and no data
class IOInterface
{
public:
    virtual int open(int opt) = 0;
    virtual int close(int opt) = 0;
    virtual int read(char* p, int n) = 0;
    virtual int write(const char* p, int n) = 0;
};


 between pointers and references
  • reference must always be initialized because the object it refers to already exists; a pointer can be left uninitialized (though is not recommended)
  • There’s no such thing a s a “NULL reference” because a reference must always refer to some object, so the “no object” concept makes no sense; pointers, as we all know, can be NULL       
  •  References can be more efficient, because there’s no need to test the validity of a reference before using it (see above comment); pointers most often have to be tested against NULL to ensure there are valid objects behind them.
  • Pointers may be reassigned to point to different objects (except constant pointers, of course), but references cannot be (references are “like” constant pointers that are automatically dereferenced by the compiler)
  • References are tied to someone else’s storage (memory) while pointers have their own storage they account for.



would you use a reference?
  • You should use a reference when you certainly know you have something to refer to, when you never want to refer to anything else.
  • Do not use references just to reduce typing. That (and that being the sole reason) is not an appropriate usage of the reference concept in C++; using references having in mind just the reason of reduced typing would lead you to a “reference spree” – it must be clear in one’s mind when to use references and when to use pointers; overusing any of the two is an inefficient path.
differences between new & malloc?
  • new” is an operator built-in into the C++ language, “malloc” is a function of the C standard library
  • “new” is aware of constructors/destructors, “malloc”
string* array1 = static_cast(malloc(10 * sizeof(string)));
free(array1);


array1 in the above example points to enough memory to hold 10 strings but no objects have been constructed and there’s no easy and clean (proper) way from OO point of view to initialize them.








 The call to free() deallocates the memory but does not destroy the objects (supposing you managed to initialize them).
string* array2 = new string[10];
delete[] array2;
array2 points to 10 fully constructed objects (they have not been properly initialized but they are constructed), because “new” allocates memory and also calls the string default constructor for each object. The call to the delete operator deallocates the memory and also destroys the objects.






Placement New:
  • Normal new allocates memory in heap and constructs objects tehre whereas using placement new, object construction can be done at known address.
  • With normal new, it is not known that, at what address or memory location it’s pointing to, whereas the address or memory location that it’s pointing is known while using placement new.
    • The deallocation is done using delete operation when allocation is done by new but there is no placement delete, but if it is needed one can write it with the help of destructor
new (address) (type) initializer
As we can see, we can specify an address
where we want a new object of given type 
to be constructed




// C++ program to illustrate the placement new operator
#include
using namespace std;
 
int main()
{
    // buffer on stack
    unsigned char buf[sizeof(int)*2] ;
 
    // placement new in buf
    int *pInt = new (buf) int(3);
 
    int *qInt = new (buf + sizeof (int)) int(5);
}



// supposing a "buffer" of memory large enough for 
// the object we want to construct was 
// previously allocated using malloc
MyClass* myObject = new (buffer) MyClass(string& name);


// !!ERROR
delete myObject;
// the correct way is
myObject->~MyClass();
// then the "buffer" must also be properly
// deallocated
free(buffer);



“virtual constructor”?[kyky]
  • There is no such thing as a virtual constructor in C++ simply because you need to know the exact type of the object you want to create and virtual represent the exact opposite concept (***)











No comments:

Post a Comment