Is virtual constructor possible:
Virtual constructor is not possible. Virtual has to be used when we don't know the exact type of object and only reference is there to call it. But while creating object we need exact type to create that's why virtual constructor is not possible.
#include <iostream>
using namespace std;
class Base{
virtual Base(){
cout<<"virtual constructor"<<endl;
}
};
class Derived : public Base{
Derived(){
cout<<"Derived constructor"<<endl;
}
};
int main()
{
Derived d;
}
How to Stop from creating Objects of a class:
In order to restrict users from creating objects of a class define the constructor as private of the class. As the object cannot call private functions of the class. It restricts the object creation as constructor call is restricted.
#include <iostream>
using namespace std;
class Derived{
Derived(){
cout<<"Derived constructor"<<endl;
}
};
int main()
{
Derived d;
}
Compilation failed due to following error(s).
main.cpp: In function ‘int main()’:
main.cpp:23:13: error: ‘Derived::Derived()’ is private within this context
Derived d;
What is pure virtual function:
Pure virtual function is being used when we need to create abstract class where Objects of it can't be created. A pure virtual function can be declared as:
virtual void func() = 0;
If a derived class doesn't override the pure virtual function, then it also becomes abstract class.
class Base{public:
Base(){
cout<<"virtual constructor"<<endl;
}
virtual void func() = 0;
};
class Derived : public Base{
public:
Derived(){
cout<<"Derived constructor"<<endl;
}
};
int main()
{
Derived *d = (Derived*)new Base();
}
main.cpp: In function ‘int main()’:
main.cpp:29:37: error: invalid new-expression of abstract class type ‘Base’
Derived *d = (Derived*)new Base();
Below code works well and doesn't create any problems:
class Base{
public:
Base(){
cout<<"virtual constructor"<<endl;
}
virtual void func() = 0;
};
class Derived : public Base{
public:
Derived(){
cout<<"Derived constructor"<<endl;
}
void func(){}
};
int main()
{
Derived *d = (Derived*)new Derived();
}
public:
Base(){
cout<<"virtual constructor"<<endl;
}
virtual void func() = 0;
};
class Derived : public Base{
public:
Derived(){
cout<<"Derived constructor"<<endl;
}
void func(){}
};
int main()
{
Derived *d = (Derived*)new Derived();
}
main.cpp:13:18: error: constructors cannot be declared ‘virtual’ [-fpermissive]
Comments
Post a Comment