Base class with a vector<int> member - c++

I'm trying to create an abstract base class that I intend the derive classes to implement a vector<int> member. My problem is if I try to do this:
class BaseClass
{
public:
virtual int GetCount() = 0;
virtual vector<int> ChildData;
}
class CID1 : public BaseClass
{
public:
int GetCount()
{
return 3;
}
//and so on.....
}
I get
'virtual' not permitted on data declarations
'virtual' is not allowed.
What I'm trying to do is:
make my child classes override the vector because they will contain different number of the vector elements
To be able to loop through an array of BaseClass* containing addresses of declared child classes, and the second loop for the data of the vectors.
Am I doing it the right way? Thanks in advance!
Note: I have no prior experience in coding in C++.

Am I doing it the right way?
No.
As the compiler lets you know, you can have virtual member functions but not virtual member variables.
Change the member variables to member functions and make sure you implement them properly in the derived classes.
class BaseClass
{
public:
virtual int GetCount() = 0;
virtual vector<int>& GetChildData() = 0;
}
class CID1 : public BaseClass
{
public:
// virtual keyword is not necessary here
// but helps with understanding code.
virtual int GetCount()
{
return 3;
}
virtual vector<int>& GetChildData()
{
return data;
}
private:
vector<int> data;
}

Related

Is there a way to override C++ class virtual functions to make them static?

So I have an abstract class, that I want two classes to derive from. I want DerivedA to implement the same behavior as DerivedB but I want to override the methods in DerivedA such that they apply to all instances, so I want to make them static. Is there a way to do this while keeping DerivedB's functionality unique to each of it's own instances? My end goal is to keep DerivedA static as a lot of the codebase already depends on it being that way. Do I need to implement an interface or will I simply need to redefine two different classes?
class AbstractBase
{
int numPlayers;
public:
virtual void setNumPlayers(int num) { numPlayers = num };
virtual int getNumPlayers() { return numPlayers; }
};
class DerivedA : public AbstractBase
{
int numPlayers;
public:
static void setNumPlayers(int num) ;
static int getNumPlayers();
};
// I don't want to have to redefine the functionality here
class DerivedB : public AbstractBase
{
int numPlayers;
public:
void setNumPlayers(int num);
int getNumPlayers();
};

C++ calling a parent class function that uses an overriden function

So I was wondering if it is possible in C++ to call a parent class method that uses an overridden method without using the parent version of the overridden method. (I know this is unclear so I made an example!)
For example, below I would like to call class A's version of findPath() from an object of class B, while using the addPoint method that is defined by class B. Currently, if I call findPath() from an object of class B, it uses the addPoint method defined in class A.
Actual Output:
A.findPath(), path = {1,2,3,4,5,6,7,8,9,10)
B.findPath(), path = {1,2,3,4,5,6,7,8,9,10)
Desired Output:
A.findPath(), path = {1,2,3,4,5,6,7,8,9,10}
B.findPath(), path = {2,4,9,16,25,36,49,64,81,100}
class A
{
public:
vector<int> path;
void addPoint(int num) {
path.push_back(num);
}
vector<int> findPath() {
for (int i = 0; i < 10; i++) {
addPoint(i);
}
}
};
class B : public A
{
public:
void addPoint(int num) {
path.push_back(num*num);
}
};
At the moment, I am copying and pasting findPath into class B to get the desired output, but I feel like there should be an easier way. Thanks!
You need to use virtual in the base class. You should also add override in the derived class, compare the CppCoreGuidelines.
class A
{
public:
...
virtual void addPoint(int num) {
path.push_back(num);
}
...
};
class B : public A
{
public:
void addPoint(int num) override {
path.push_back(num*num);
}
};
It is possible. This is known as the Template Method Pattern. The name is a bit unfortunate, because it has nothing to do with C++ templates. A base class can implement something and derived classes only override the individual steps of the bigger "something".
For example:
struct Base {
virtual void stepA() = 0;
virtual void stepB() = 0;
virtual void stepC() = 0;
void do_something_complicated() {
stepA();
stepB();
stepC();
}
};
Derived classes only override the methods for the individual steps, while they are composed in the base class already.
In your example you forgot to declare addPoint as virtual, A should have a virtual destructor and using override is recommended to let the compiler help you in case of mistakes:
class A
{
public:
vector<int> path;
virtual void addPoint(int num) {
path.push_back(num);
}
vector<int> findPath() { // () was missing
for (int i = 0; i < 10; i++) {
addPoint(i);
}
return path; // return was missing
}
virtual ~A() = default;
};
class B : public A
{
public:
void addPoint(int num) override {
path.push_back(num*num);
}
};

Abstract class methods implementation with subclasses of an other base class

I am trying to define an interface called "Algorithm" which has a pure virtual method insertData(InputData* input).
The implementation of the interface is called "Algorithm1" and i want to implement method "insertData" using as a parameter "SpecificData" which is a child of "InputData" class.
Is it possible without type casting?
Obviously with this code i get an error from the compiler that the virtual function "insertData" is pure within "Algorithm1".
class Algorithm{
public:
virtual ~Algorithm();
virtual void insertData(InputData* input) = 0;
};
class Algorithm1 : public Algorithm{
public:
Algorithm1();
virtual ~Algorithm1();
void insertData(SpecificData* input){
input.getID();
input.getAdditionalNumbers;
/*Process input information etc.*/ };
};
class InputData{
public:
void setID(int id){ this->id = id; }
int getID(){ return id;};
private:
int id;
};
class SpecifiData : public InputData{
public:
list<int> getAdditionalNumbers(){/*Return various Numbers*/};
private:
list<int> extraInfo;
};
void main(){
SpecificData* data = new SpecificData();
Algorithm* alg = new Algorithm1();
alg->insertData(data);
}
For insertData to be the same function (rather than "hiding" the original insertData, you need the two functions to have the same arguments (and same return type).
The whole idea of interfaces using virtual functions is that "they appear the same from the outside". You should be able to build a list of objects, and perform the same operation with the same input data for all of the objects in the list.
If you are breaking that principle, you are "doing it wrong".
No, it wouldn't make sense.
Think about the following scenario - you have a container (vector/set w/e) of Algorithm* type objects and a function that takes this container and a InputData* in as an input and then iterate over them and call insertData(in) on each of the objects in the container, this of course should work properly, but if one of the objects in your container is of type Algorithm1 what will happen then?
I think, this is a typical example of "Factory Method" in design pattern term.
class Algorithm
{
public:
virtual ~Algorithm();
virtual void insertData(InputData* input) = 0;
};
class InputData
{
public:
void setID(int id){ this->id = id; }
int getID(){ return id;};
virtual list<int> getAdditionalNumbers() = 0;
private:
int id;
};
class Algorithm1 : public Algorithm
{
public:
Algorithm1();
virtual ~Algorithm1();
void insertData(InputData* input){
input.getID();
input.getAdditionalNumbers;
/*Process input information etc.*/ };
};
class SpecifiData : public InputData
{
public:
// implementation
virtual list<int> getAdditionalNumbers(){/*Return various Numbers*/};
private:
list<int> extraInfo;
};
void main()
{
InputData* data = new SpecificData();
Algorithm* alg = new Algorithm1();
alg->insertData(data);
}

exporting class from dll error

I want to expose only the CreateSort() for the client. it was to create an object for the implementation of the sort class i.e imSort then return it to the client.but the compiler says that it cannot create an object of an abstract class eventhough all the functions have been defined in the derived class.
/////sort.h
class __declspec(dllexport) Sort {
public:
virtual int* BSort() const=0;
virtual void getdata() const=0;
};
extern "C" Sort *CreateSort();
/////imSort.h
#include "Sort.h"
class imSort : public Sort{
private:
int i,j,num;
int temp;
int *a;
public:
imSort();
int* BSort();
void getdata();
}
/////imSort.cpp
#include <iostream>
#include "imSort.h"
Sort *CreateSort()
{
return new imSort(); /* object of abstract class type "imSort" is not allowed: */
}
imSort::imSort()
{
i=j=num=0;
*a=0;
}
void imSort::getdata()
{
std::cout<<"\nEnter the number of elements..";
std::cin>>num;
for(i=0;i<num;i++)
{
std::cin>>*a;
*(a++);
}
}
int* imSort::BSort()
{
for(i=0;i<num;i++)
for(j=i+1;j<num;j++)
{
if(*(a+i)<*(a+j))
{
temp=*(a+i);
*(a+i)=*(a+j);
*(a+j)=temp;
}
}
return a;
}
Your base class has:
virtual int* BSort() const=0;
virtual void getdata() const=0;
But your derived class has:
int* BSort();
void getdata();
Repeating the virtual keyword is optional, but without the const these are separate functions, unrelated to the virtual base functions.
As a result, those pure virtual functions remain un-overridden in the derived class, and so imSort (silly name for a type if you ask me) is still abstract.
Your fixed derived class definition is thus:
class imSort : public Sort {
private:
int i, j, num;
int temp;
int* a;
public:
imSort();
int* BSort() const; // <--- const
void getdata() const; // <--- const
}; // <--- ;
(Notice how indentation improves the legibility of your code? And you forgot the ; at the end of your class definition.)
Please write a fully-formed question next time, and reduce your problem to a minimal testcase.
If the virtual functions in the abstract Sort class are declared const, so should the implementations in the imSort class, but they are not.
So just add const here and there...

Multiple declaration for function

I have a function declared in my base class and specified as virtual, I am trying to re-declare it in a derived class but I'm getting a multiple declaration error.
Anyone know if I'm missing something here?
class Field {
public:
virtual void display() = 0;
virtual int edit() = 0;
virtual bool editable() const = 0;
virtual void *data() = 0;
virtual Field *clone() const = 0;
};
class LField : public Field {
int rowNum;
int colNum;
int width;
char *val;
bool canEdit;
int index;
public:
virtual void *data() { return val; }
};
class IVField : public LField {
void (*ptrFunc)(void *);
bool (*ptrValid)(int &);
int *data;
public:
void* data() {
return data;
}
};
class DVField : public LField {
int decimalsToDisplay;
double *data;
void (*ptrFunc)(void *);
bool (*ptrValid)(double&);
public:
void* data() {
return data;
}
};
You have a function named data and a member variable named data in the same class. That's not allowed. Pick a different name for your member variable.
You also appear to be re-declaring many member variables. That's probably not what you want to do. If you want to declare them in the base class and use them in descendants, then they should probably have protected visibility. The default visibility for classes, when you haven't specified any other, is private, which means, for example, that descendants of IVField (such as DVField) cannot access the ptrFunc variable you declared in IVField. The ptrFun variable you declared in DVField has absolutely no relation to the one declared in the parent class. Make the IVField one protected, and then descendants don't need to duplicate the declaration for themselves.
You're also going to have to implement all those other abstract methods before the compiler will allow you to instantiate any of those classes.