In the second class I want to only add numbers to string, and I am getting the error "main.cpp:38:19: error: ‘virtual void NumericInput::add(char)’ is private within this context 38 | input->add('1');' for every time I class add for Numeric object. What did I do wrong here, isn't everything already public? Thank you!!
#include <string>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
using namespace std;
class TextInput
{
public:
string s="";
virtual void add(char c)
{
s =c;
}
string getValue()
{
return s;
}
};
class NumericInput : public TextInput
{
//modified
void add(char c)
{
if(isdigit(c))
{
s =c;
}
}
};
int main()
{
NumericInput* input = new NumericInput();
input->add('1');
input->add('a');
input->add('0');
cout<<input->getValue();
}
CodePudding user response:
All declarations in a class are private by default if there's no public access specifier. You should also override your virtual function in NumericInput.
CodePudding user response:
Add public before in NumericInput
class NumericInput : public TextInput
{
public:
//modified
void add(char c)
{
if(isdigit(c))
{
s =c;
}
}
};