C++ Basic Concept

1. Constructor & Destructor

Q: Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?

A: There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructor

is a code which is responsible for creating an instance of a class and it can’t be delegated to

any other object by virtual keyword means.

Q: What about Virtual Destructor?

A: Yes there is a Virtual Destructor. A destructor can be virtual as it is possible as at runtime

depending on the type of object caller is calling to, proper destructor will be called.

Q: What is copy constructor?

A: Constructor which initializes the it's object member variables ( by

shallow copying) with another object of the same class. If you don't implement one in your class

then compiler implements one for you. for example:

(a) Boo Obj1(10); // calling Boo constructor

(b) Boo Obj2(Obj1); // calling boo copy constructor

(c) Boo Obj2 = Obj1;// calling boo copy constructor

Q: When are copy constructors called?

A: Copy constructors are called in following cases:

(a) when a function returns an object of that

class by value

(b) when the object of that class is passed by

value as an argument to a function

(c) when you construct an object based on another

object of the same class

(d) When compiler generates a temporary object


2. Virtual

Q: What is virtual function?

A: When derived class overrides the base class method by redefining the same function, then if

client wants to access redefined the method from derived class through a pointer from base class

object, then you must define this function in base class as virtual function.

class parent {

    void Show( ) {

        cout << "i'm parent" << endl;

    }

};

class child :  public parent {

    void Show( ) {

        cout << "i'm child" << endl;

}

};

parent * parent_object_ptr = new child;

parent_object_ptr->show() // calls parent->show()

now we goto virtual world...

class parent {

    virtual void Show( ) {

        cout << "i'm parent" << endl;

    }

};

class child : public parent {

    void Show( ) {

        cout << "i'm child" << endl;

    }

};

parent * parent_object_ptr = new child;

parent_object_ptr->show() // calls child->show()


Q: What is a "pure virtual" member function?

A: The abstract class whose pure virtual method has to be implemented by all the classes which

derive on these. Otherwise it would result in a compilation error. This construct should be used

when one wants to ensure that all the derived classes implement the method defined as pure

virtual in base class.

Q: How virtual functions are implemented C++?

A: Virtual functions are implemented using a table of function pointers, called the vtable. There

is one entry in the table per virtual function in the class. This table is created by the constructor

of the class. When a derived class is constructed, its base class is constructed _rst which creates

the vtable. If the derived class overrides any of the base classes virtual functions, those entries in

the vtable are overwritten by the derived class constructor. This is why you should never call

virtual functions from a constructor: because the vtable entries for the object may not have

been set up by the derived class constructor yet, so you might end up calling base class

implementations of those virtual functions

Q: What is pure virtual function? or what is abstract class?

A: When you de_ne only function prototype in a base class without implementation and do the

complete implementation in derived class. This base class is called abstract class and client won't

able to instantiate an object using this base class. You can make a pure virtual function or

abstract class this way..

class Boo {

    void foo() = 0;

}

Boo MyBoo; // compilation error

Q: What is Pure Virtual Function? Why and when it is used?

A: The abstract class whose pure virtual method has to be implemented by all the classes which

derive on these. Otherwise it would result in a compilation error. This construct should be used

when one wants to ensure that all the derived classes implement the method defined as pure

virtual in base class.

3. Inheritance

Q: What is inheritance?

A: Inheritance allows one class to reuse the state and behavior of another class. The derived class

inherits the properties and method implementations of the base class and extends it by overriding

methods and adding additional properties and methods.

Q: What is multiple inheritance(virtual inheritance)? What are its advantages and disadvantages?

A: Multiple Inheritance is the process whereby a child can be derived from more than one parent

class. The advantage of multiple inheritance is that it allows a class to inherit the functionality of

more than one base class thus allowing for modeling of complex relationships.

The disadvantage of multiple inheritance is that it can lead to a lot of confusion(ambiguity)

when two base classes implement a method with the same name.

4. Polymorphism

Q: What is Polymorphism?

A: Polymorphism allows a client to treat different objects in the same way even if they were

created from different classes and exhibit different behaviors. You can use implementation

inheritance to achieve polymorphism in languages such as C++ and Java. Base class object's

pointer can invoke methods in derived class objects. You can also achieve polymorphism in

C++ by function overloading and operator overloading.

5. Class

Q: What are the differences between a C++ struct and C++ class?

A: The default member and base class access specifies are different. This is one of the

commonly misunderstood aspects of C++. Believe it or not, many programmers think that a C++

struct is just like a C struct, while a C++ class has inheritance, access specifes, member

functions, overloaded operators, and so on. Actually, the C++ struct has all the features of the

class. The only differences are that a struct defaults to public member access and public base

class inheritance, and a class defaults to the private access specified and private base-class

inheritance.

Q: What is encapsulation?

A: Containing and hiding Information about an object, such as internal data structures and code.

Encapsulation isolates the internal complexity of an object's operation from the rest of the

application. For example, a client component asking for net revenue from a business object need

not know the data's origin.

Q: What is Overriding?

A: To override a method, a subclass of the class that originally declared the method must declare

a method with the same name, return type (or a subclass of that return type), and same parameter list.

The definition of the method overriding is:

· Must have same method name.

· Must have same data type.

· Must have same argument list.

Overriding a method means that replacing a method functionality in child class. To imply

overriding functionality we need parent and child classes. In the child class you define the same

method signature as one defined in the parent class.


6.  Memory Allocation/ Deallocation

Q: What is the difference between new/delete and malloc/free?

A: malloc allocates memory for object in heap but doesn't invoke object's constructor to initialize

the object. new allocates memory and also invokes constructor to initialize the object. malloc()

and free() do not support object semantics, does not construct and destruct objects

Eg. string * ptr = (string *)(malloc (sizeof(string))) Are not safe, and does not calculate the size

of the objects that it construct

The following return a pointer to void

int *p = (int *) (malloc(sizeof(int)));

int *p = new int;

Are not extensible

new and delete can be overloaded in a class

"delete" first calls the object's termination routine (i.e. its destructor) and then releases the space

the object occupied on the heap memory. If an array of objects was created using new, then

delete must be told that it is dealing with an array by preceding the name with an empty []:-

Int_t *my_ints = new Int_t[10];

...

delete []my_ints;

Q: What is the difference between delete and delete[]?

A: Whenever you allocate memory with new[], you have to free the memory using delete[].

When you allocate memory with 'new', then use 'delete' without the brackets. You use new[] to

allocate an array of values (always starting at the index 0).


7. Pointer

Q: What is the difference between a pointer and a reference?

A: A reference must always refer to some object and, therefore, must always be initialized;

pointers do not have such restrictions. A pointer can be reassigned to point to different objects

while a reference always refers to an object with which it was initialized.

Q: When should I use references, and when should I use pointers?

A: Use references when you can, and pointers when you have to.

References are usually preferred over pointers whenever you don't need "reseating". This usually

means that references are most useful in a class's public interface. References typically appear on

the skin of an object, and pointers on the inside.

The exception to the above is where a function's parameter or return value needs a "sentinel"

reference a reference that does not refer to an object. This is usually best done by

returning/taking a pointer, and giving the NULL pointer this special significance (references

should always alias objects, not a dereferenced NULL pointer).

Note: Old line C programmers sometimes don't like references since they provide reference

semantics that isn't explicit in the caller's code. After some C++ experience, however, one

quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g.,

programmers should write code in the language of the problem rather than the language of the

machine.

Q: What is a smart pointer?

A: A smart pointer is a C++ class that mimics a regular pointer in syntax and some semantics,

but it does more. Because smart pointers to different types of objects tend to have a lot of code in common, almost all good-quality smart pointers in existence are templated by the pointee type.

Q: What is auto pointer?

A: The simplest example of a smart pointer is auto_ptr, which is included in the standard C++

library. Auto Pointer only takes care of Memory leak and does nothing about dangling pointers

issue. You can find it in the header . Here is part of auto_ptr's implementation.

8. Overload

Q: What is overloading??

A: With the C++ language, you can overload functions and operators. Overloading is the

practice of supplying more than one definition for a given function name in the same scope.

- Any two functions in a set of overloaded functions must have different argument lists.

- Overloading functions with argument lists of the same types, based on return type alone, is an

error.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,670评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,928评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,926评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,238评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,112评论 4 356
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,138评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,545评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,232评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,496评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,596评论 2 310
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,369评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,226评论 3 313
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,600评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,906评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,185评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,516评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,721评论 2 335

推荐阅读更多精彩内容