You don't pay for what you don't use

One of the mottos of C++ is You don't pay for what you don't use. This language is packed with many more features than C, yet it promises zero overhead for those that are not used. 

Take, for example, virtual functions:

#include <iostream>

class A {

public:

void print() {

std::cout << "A" << std::endl;

}

};

class B: public A {

public:

void print() {

std::cout << "B" << std::endl;

}

};

int main() {

A* obj = new B;

obj->print();

}

The preceding code will output A, despite obj pointing to the object of the B class. To make it work as expected, the developer adds a keywordvirtual:

#include <iostream>

class A {

public:

virtual void print() {

std::cout << "A" << std::endl;

}

};

class B: public A {

public:

void print() {

std::cout << "B" << std::endl;

}

};

int main() {

A* obj = new B;

obj->print();

}

After this change, the code outputs B, which is what most developers expect to get as a result. You may ask why C++ does not enforce every method to be virtual by default. This approach is adopted by Java and doesn't seem to have any downsides.

The reason is that virtual functions are not free. Function resolution is performed at runtime via the virtual table—an array of function pointers. It adds a slight overhead to the function invocation time. If you do not need dynamic polymorphism, you do not pay for it. That is why C++ developers add the virtual keyboard, to explicitly agree with functionality that adds performance overhead.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.111.85