← Back to C++ Course | Chapter 17: Advanced C++ | Lesson 2 of 17

C++ Interview Questions

What is a Virtual Function?

A virtual function is declared in a base class using the virtual keyword and can be overridden by derived classes; calling it through a base-class pointer or reference invokes whichever derived-class version actually matches the object's real type at runtime -- this is the mechanism behind runtime polymorphism.

Example: What is a Virtual Function?

cpp
#include <iostream>

class Animal {
public:
	virtual void speak() { std::cout << "..." << std::endl; }
};

class Dog : public Animal {
public:
	void speak() override { std::cout << "Woof" << std::endl; }
};

int main() {
	Animal *a = new Dog();
	a->speak();
	delete a;
	return 0;
}

Pointer vs. Reference

A pointer stores a memory address and can be reassigned to point elsewhere, or set to nullptr to represent "no target." A reference is an alias for an existing variable -- it must be bound at the moment it's declared and can never be reseated to refer to something else afterward.

Example: Pointer vs. Reference

cpp
#include <iostream>

int main() {
	int a = 5, b = 10;
	int *ptr = &a;
	ptr = &b;
	int &ref = a;
	std::cout << *ptr << " " << ref << std::endl;
	return 0;
}

What is a Constructor?

A constructor is a special member function with the same name as its class, called automatically the instant an object is created, whose job is to put that object into a valid initial state -- typically by initializing its member variables from arguments or defaults.

Example: What is a Constructor?

cpp
#include <iostream>

class Car {
public:
	Car() { std::cout << "Car constructed" << std::endl; }
};

int main() {
	Car car;
	return 0;
}

Struct vs. Class

In C++, struct and class are functionally identical except for one default: members of a struct are public unless stated otherwise, while members of a class are private unless stated otherwise. Convention still uses struct for simple data-holding types and class for types with real behavior.

Example: Struct vs. Class

cpp
#include <iostream>

struct Point { int x; };
class Box { int size; };

int main() {
	Point p;
	p.x = 5;
	std::cout << p.x << std::endl;
	return 0;
}

What is nullptr?

nullptr, introduced in C++11, is a type-safe null pointer literal that fixes a long-standing ambiguity from C's use of the integer 0 (or the NULL macro) to represent "no pointer," particularly around overload resolution where an int and a pointer parameter could both accidentally match plain 0.

Example: What is nullptr?

cpp
#include <iostream>

int main() {
	int *ptr = nullptr;
	std::cout << (ptr == nullptr) << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.