How to use pure virtual function in C++

3 Answers

0 votes
#include <iostream>
#include <fstream>

class Base {
public:
    virtual std::string GetName() = 0; // pure virtual function
};


class Example : public Base {
private:
    std::string m_Name;
public:
    Example(const std::string& name)
        : m_Name(name) {}

    std::string GetName() override { return m_Name; } // have to implement
};

int main() {
    // Base* b = new Base(); // Error: object of abstract class type "Base" is not allowed: 
                             //        function "Base::GetName" is a pure virtual function

    Example* e = new Example("Example");
    std::cout << e->GetName() << "\n";
}




/*
run:

Example

*/

 



answered Jan 29, 2023 by avibootz
0 votes
#include <iostream>
#include <fstream>

class Print {
public:
    virtual std::string GetClassName() = 0; // pure virtual function
};

class Base : public Print {
public:
    virtual std::string GetClassName() override  { return "Base"; } // have to implement
};


class Example : public Base {
public:
    virtual std::string GetClassName() override { return "Example"; } // have to implement
};

int main() {
    // Print* p = new Print(); // Error: object of abstract class type "Print" is not allowed: 
                               //        function "Print::GetClassName" is a pure virtual function

    Base* b = new Base();
    std::cout << b->GetClassName() << "\n";

    Example* e = new Example();
    std::cout << e->GetClassName() << "\n";
}




/*
run:

Base
Example

*/

 



answered Jan 29, 2023 by avibootz
edited Jan 29, 2023 by avibootz
0 votes
#include <iostream>
#include <fstream>

class Print {
public:
    virtual std::string GetClassName() = 0; // pure virtual function
};

class Base : public Print {
public:
    virtual std::string GetClassName() override  { return "Base"; } // have to implement
};


class Example : public Base {
public:
    virtual std::string GetClassName() override { return "Example"; } // have to implement
};

void Show(Print* p) {
    std::cout << p->GetClassName() << "\n";
}


int main() {
    // Print* p = new Print(); // Error: object of abstract class type "Print" is not allowed: 
                               //        function "Print::GetClassName" is a pure virtual function

    Base* b = new Base();
    Show(b);

    Example* e = new Example();
    Show(e);
}




/*
run:

Base
Example

*/

 



answered Jan 29, 2023 by avibootz

Related questions

1 answer 186 views
1 answer 197 views
1 answer 180 views
2 answers 235 views
2 answers 169 views
169 views asked Mar 31, 2018 by avibootz
...