New to Cpp. In the given code, I don't know what change_val(int k) = 0;
means and why the compiler prints
error: cannot declare variable 'ob1' to be of abstract type 'B'
B ob1(10);
error: invalid new-expression of abstract class type 'B'
ob2 = new B(100);
To my knowledge, neither B
nor A
has been declared abstract. Then why can't I declare a variable of B object? And is it possible to assign object of one class to another object type as in A *ob2; ob2 = new B(100);
?
The code:
#include<iostream>
using namespace std;
class A{
int x;
public:
A(){x=0;}
explicit A(int x){ cout<<"Constructor of A called"<<endl;
this->x = x+100;}
virtual void change_val(int k) = 0;
void set_x(int k){x = k;}
int get_val() const{ return x; }
virtual void print_value()
{
cout<<x<<endl;
}
};
class B : public A{
public:
explicit B(int k):A(k){
cout<<"Constructor of B called"<<endl;
}
void print_value() override
{
cout<< get_val()+200<<endl;
}
};
int main(){
B ob1(10);
ob1.print_value ();
A *ob2;
ob2 = new B(100);
ob2->print_value ();
ob2->change_val(20);
ob2->print_value ();
}