C++ Interview Questions(2025)

author image Hirely
at 06 Jan, 2025

Question: What are templates in C++?

Answer:

Templates in C++ allow for the creation of generic functions and generic classes, enabling code to be written in a way that is independent of data types. Templates allow you to define functions, classes, or structures that can work with any data type, and the type is specified when the function or class is used. This feature helps to create flexible and reusable code that works with different types without duplication.

Templates are one of the key features in C++ to support generic programming, which allows for the writing of type-independent code. There are two primary types of templates in C++:

  1. Function Templates: These allow you to define a function that can operate on different types of data.
  2. Class Templates: These allow you to define a class that works with different data types.

1. Function Templates

A function template is a blueprint for creating functions that can work with any data type. The syntax for defining a function template includes the template keyword followed by a type parameter enclosed in angle brackets (<>).

Example:

#include <iostream>
using namespace std;

// Function template to add two values
template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    cout << add(5, 10) << endl;         // Calls add<int>(int, int)
    cout << add(3.5, 2.5) << endl;      // Calls add<double>(double, double)
    cout << add('A', 1) << endl;        // Calls add<char>(char, char)

    return 0;
}

Output:

15
6
B

In this example:

  • The add function is a template that works with any data type (such as int, double, char).
  • The typename T in the template declaration specifies that T is a placeholder for the data type.
  • When you call add, the compiler automatically determines the type for T based on the arguments passed.

2. Class Templates

Class templates allow you to define a class that can work with any data type. Like function templates, class templates use the template keyword and a type parameter.

Example:

#include <iostream>
using namespace std;

// Class template to store a pair of values
template <typename T>
class Pair {
private:
    T first, second;
public:
    Pair(T a, T b) : first(a), second(b) {}

    T getFirst() { return first; }
    T getSecond() { return second; }
};

int main() {
    Pair<int> intPair(1, 2);            // Pair of ints
    cout << intPair.getFirst() << " " << intPair.getSecond() << endl;  // Output: 1 2

    Pair<double> doublePair(3.5, 4.5);   // Pair of doubles
    cout << doublePair.getFirst() << " " << doublePair.getSecond() << endl;  // Output: 3.5 4.5

    return 0;
}

Output:

1 2
3.5 4.5

In this example:

  • Pair is a template class that can store a pair of values of any data type.
  • The type T is defined when creating an object of Pair.

3. Template Specialization

Sometimes, you may want to provide a specialized implementation of a template for a specific type. This is known as template specialization. Template specialization allows you to define different behaviors for different data types.

Example of Specializing a Function Template:

#include <iostream>
using namespace std;

// Generic function template
template <typename T>
void print(T val) {
    cout << "Generic: " << val << endl;
}

// Template specialization for int
template <>
void print<int>(int val) {
    cout << "Specialized for int: " << val << endl;
}

int main() {
    print(42);       // Calls specialized version for int
    print(3.14);     // Calls generic version

    return 0;
}

Output:

Specialized for int: 42
Generic: 3.14

In this example:

  • We define a generic print function template.
  • Then, we specialize the template for the int type, so when the argument is of type int, the specialized version is called.

Example of Specializing a Class Template:

#include <iostream>
using namespace std;

// Class template
template <typename T>
class Box {
public:
    T value;
    Box(T v) : value(v) {}
    void print() { cout << "Generic Box: " << value << endl; }
};

// Specialization of Box for char type
template <>
class Box<char> {
public:
    char value;
    Box(char v) : value(v) {}
    void print() { cout << "Specialized Box for char: " << value << endl; }
};

int main() {
    Box<int> intBox(10);   // Generic Box for int
    intBox.print();         // Output: Generic Box: 10

    Box<char> charBox('A'); // Specialized Box for char
    charBox.print();        // Output: Specialized Box for char: A

    return 0;
}

Output:

Generic Box: 10
Specialized Box for char: A

In this example:

  • We define a template class Box that works with any data type.
  • We specialize Box for char to provide a different behavior.

4. Variadic Templates

C++11 introduced variadic templates, which allow you to write templates that can accept an arbitrary number of template parameters. This is useful when you don’t know in advance how many arguments you need.

Example of Variadic Template:

#include <iostream>
using namespace std;

template <typename... Args>
void print(Args... args) {
    (cout << ... << args) << endl;  // Fold expression to print all arguments
}

int main() {
    print(1, 2.5, "hello", 'a');  // Output: 12.5helloa
    return 0;
}

Output:

12.5helloa

In this example:

  • The print function is a variadic template that can accept any number of arguments and prints them all.

Advantages of Templates:

  • Code Reusability: Templates allow the same code to be used for different data types without duplication.
  • Type Safety: Templates provide type checking at compile-time, ensuring that only compatible types are used.
  • Efficiency: Since templates are instantiated at compile time, they avoid runtime overhead.

Summary

FeatureDescription
DefinitionTemplates allow writing generic functions or classes that can operate on any data type.
TypesFunction templates, class templates, variadic templates.
Template SpecializationAllows providing a different implementation for a specific data type.
AdvantagesCode reusability, type safety, and compile-time efficiency.
Use CasesGeneric data structures, algorithms, and functions.

Templates in C++ are powerful tools that enable the development of flexible, reusable, and efficient code for various data types without having to rewrite code for each specific type.

Question: What is the difference between a struct and a class in C++?

Answer:

In C++, both struct and class are used to define user-defined data types that can hold multiple data members and functions. They are similar in many ways, but there are a few key differences primarily related to default access specifiers and inheritance. Here’s a detailed breakdown of the differences:

1. Default Access Specifiers

  • Struct: In a struct, members (both data members and member functions) are public by default.
  • Class: In a class, members are private by default.

Example:

struct MyStruct {
    int x; // public by default
    void display() {
        std::cout << "x = " << x << std::endl;
    }
};

class MyClass {
    int y; // private by default
public:
    void setY(int val) { y = val; }
    void display() {
        std::cout << "y = " << y << std::endl;
    }
};

In this example:

  • In MyStruct, the member x and function display() are public by default.
  • In MyClass, the member y is private by default, but we make it accessible through the public function setY().

2. Inheritance Access Modifiers

  • Struct: In a struct, inheritance is public by default.
  • Class: In a class, inheritance is private by default.

Example:

struct BaseStruct {
    int x;
};

struct DerivedStruct : BaseStruct {
    // Inherits x as public by default
};

class BaseClass {
    int y;
};

class DerivedClass : BaseClass {
    // Inherits y as private by default
};

In this example:

  • In DerivedStruct, x is inherited as public from BaseStruct.
  • In DerivedClass, y is inherited as private from BaseClass.

3. Intended Use

  • Struct: struct is typically used for simple data structures that are meant to hold data with little or no behavior (i.e., no member functions). It is ideal for plain-old-data (POD) types where you want to keep things lightweight.
  • Class: class is used for more complex types, typically those that encapsulate both data and behavior (i.e., data members and member functions). It supports object-oriented features such as encapsulation, polymorphism, and inheritance.

4. Inheritance and Polymorphism

  • Both struct and class support inheritance and polymorphism in C++, but the default access specifiers (discussed earlier) affect how inheritance behaves.

5. Memory Layout

  • Memory layout: There is no significant difference between a struct and a class in terms of memory layout in C++. Both struct and class can have data members of any type (including other structs or classes) and their layout in memory is essentially the same. The only distinction is the default access modifier behavior.

6. Usage and Convention

  • Struct is traditionally used in C-like programming to define data structures that don’t require encapsulation (i.e., simple data containers).
  • Class is used when object-oriented principles such as encapsulation, polymorphism, and inheritance are involved.

Summary Table

Featurestructclass
Default Access ModifierPublic by defaultPrivate by default
Default Inheritance ModifierPublic by defaultPrivate by default
Typical UsageUsed for simple data structuresUsed for complex, object-oriented programming
Inheritance SupportSupports inheritance with public accessSupports inheritance with private access
Memory LayoutSame as class; no difference in memorySame as struct; no difference in memory

Conclusion:

  • The primary difference between a struct and a class in C++ lies in the default access modifiers:
    • struct: Members are public by default.
    • class: Members are private by default.

In practice, the choice between struct and class often comes down to convention. If you’re working with simple data structures that don’t need encapsulation, a struct is commonly used. If you’re implementing more complex behaviors with private data and methods, a class is the preferred choice.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as C++ interview questions, C++ interview experiences, and details about various C++ job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now