what is abstract class in c++
//Code by Soumyadeep Ghosh
//insta : @soumyadepp
//linked in : https://www.linkedin.com/in/soumyadeep-ghosh-90a1951b6/
#include <bits/stdc++.h>
using namespace std;
class person
{
string p_id;
public:
virtual void get_info()=0; //declaring person as abstract class
virtual void show()=0;
};
class student:public person
{
string name;
int roll_no;
public:
/*overriding the pure virtual function declared in base class otherwise
this class will become an abstract one and then objects cannot be created
for the same*/
void get_info()
{
cout<<"Enter name of the student "<<endl;
cin>>name;
cout<<"Enter roll number of the student "<<endl;
cin>>roll_no;
}
void show()
{
cout<<"Name : "<<name<<" Roll number: "<<roll_no<<endl;
}
};
int main()
{
person *p;
p=new student;
p->get_info();
p->show();
return 0;
}
4.8
5
struct Abstract {
virtual void f() = 0; // pure virtual
}; // "Abstract" is abstract
struct Concrete : Abstract {
void f() override {} // non-pure virtual
virtual void g(); // non-pure virtual
}; // "Concrete" is non-abstract
struct Abstract2 : Concrete {
void g() override = 0; // pure virtual overrider
}; // "Abstract2" is abstract
int main()
{
// Abstract a; // Error: abstract class
Concrete b; // OK
Abstract& a = b; // OK to reference abstract base
a.f(); // virtual dispatch to Concrete::f()
// Abstract2 a2; // Error: abstract class (final overrider of g() is pure)
}
Thank you!
5
0
4
8
struct Abstract
{
virtual ~Abstract() = 0;
};
Abstract::~Abstract() {}
struct Valid: public Abstract
{
// Notice you don't need to actually overide the base
// classes pure virtual method as it has a default
};
int main()
{
// Abstract a; // This line fails to compile as Abstract is abstract
Valid v; // This compiles fine.
}
Thank you!
8
0
Are there any code examples left?
New code examples in category C++
-
C++ 2023-04-28 17:44:25
-
C++ 2022-03-27 19:20:39 lists occurrences of characters in the string c++
-
C++ 2022-03-27 18:00:14 variabili in c++
-
C++ 2022-03-27 17:10:08 repeat character n times c++
-
C++ 2022-03-27 15:50:07 delete an array c++
-
C++ 2022-03-27 15:40:12 C++ pointer to base class
-
C++ 2022-03-27 12:15:21 find the graph is minimal spanig tree or not
-
C++ 2022-03-27 11:30:15 multi variable assignment cpp
-
C++ 2022-03-27 11:05:17 c++ pi float
-
C++ 2022-03-27 10:20:12 why exceptions can lead to memory leaks