Search
 
SCRIPT & CODE EXAMPLE
 

CPP

C++ pointer to base class

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <vector>

class Parent {
public:
    virtual void sayHi()
    {
        std::cout << "Parent here!" << std::endl;
    }
};

class Child : public Parent {
public:
    void sayHi()
    {
        std::cout << "Child here!" << std::endl;
    }
};

class DifferentChild : public Parent {
public:
    void sayHi()
    {
        std::cout << "DifferentChild here!" << std::endl;
    }
};

int main()
{
    std::vector<Parent*> parents;

    // Add 10 random children
    srand(time(NULL));
    for (int i = 0; i < 10; ++i) {
        int child = rand() % 2; // random number 0-1
        if (child) // 1
            parents.push_back(new Child);
        else
            parents.push_back(new DifferentChild);
    }

    // Call sayHi() for each type! (example of polymorphism)
    for (const auto& child : parents) {
        child->sayHi();
    }

    return 0;
}
Comment

PREVIOUS NEXT
Code Example
Cpp :: A Program to check if strings are rotations of each other or not 
Cpp :: enum in c++ 
Cpp :: declare class c++ 
Cpp :: binary to decimal 
Cpp :: raspberry pi mount external hard drive 
Cpp :: c++ get index of map element 
Cpp :: file streams in c++ 
Cpp :: pause the console c++ 
Cpp :: data type c++ 
Cpp :: double plus overload 
Cpp :: Initialize Vector Iterator with end() function 
Cpp :: qt c++ qdockwidget remove title 
Cpp :: C++ file . 
Cpp :: how to bath without water 
Cpp :: unambiguous 
Cpp :: parking charge system project c++ 
Cpp :: c++ break statement 
Cpp :: c++ throe 
Cpp :: kruskal algorithm 
Cpp :: c++ Difference Array | Range update query in O(1) 
Cpp :: is obje file binary?? 
Cpp :: txt to pdf CPP 
Cpp :: zsh: segmentation fault ./provided_files.exe erosion X . 
Cpp :: Print value of data in c++ 
Cpp :: tan trigonometric function 
Cpp :: sort vector from smallest to largest 
Cpp :: play roblox vr on quest 2 
Cpp :: left margin c++ 
Cpp :: Accepting multiple inputs on the SAME LINE C++ 
Cpp :: how to replace a element in a vector c++ using index 
ADD CONTENT
Topic
Content
Source link
Name
3+1 =