exporting class from dll error - c++

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...

Related

Access methods from derived class using an object from base class

I need to solve this problem about classes in C++. The problem says I need to create a base class, which has to be derived into 3 other derived classes. On main, I created a vector that can save objects from the base class to save the 3 different derived classes. The thing is that I don't know how to access the methods of the derivative classes when I access the vectors. For example, class C has 2 attributes and methods that base and other classes don't have, I need to have some way to access those methods using the vector of the base class. I hope someone could help me.
#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
class Base{
protected:
string placa;
int ano_de_registro;
public:
Base(){};
Base(string _placa, int _ano_de_registro):placa(_placa),ano_de_registro(_ano_de_registro){};
const string &getPlaca() const {
return placa;
}
int getAnoDeRegistro() const {
return ano_de_registro;
}
};
class A: public Base{
int cubicaje;
int caballos_de_fuerza;
int contaminacion;//0==minimo, 1==normal y 2==excesivo
public:
A(){};
A(string _placa, int _ano_de_registro, int _cubicaje, int _caballos_de_fuerza, int _contaminacion):Base(_placa,_ano_de_registro),cubicaje(_cubicaje),caballos_de_fuerza(_caballos_de_fuerza),contaminacion(_contaminacion){};
int getCubicaje() {
return cubicaje;
}
int getCaballosDeFuerza() {
return caballos_de_fuerza;
}
int getContaminacion() {
return contaminacion;
}
};
class B: public Base{
int cubicaje;
public:
B(){};
B(string _placa, int _ano_de_registro, int _cubicaje):Base(_placa,_ano_de_registro),cubicaje(_cubicaje){};
int getCubicaje() const {
return cubicaje;
}
};
class C: public Base{
int cantidad_de_ejes;
int sobregarga;
public:
C(){};
C(string _placa, int _ano_de_registro,int _cantidad_de_ejes, int _sobregarga):C(_placa,_ano_de_registro),cantidad_de_ejes(_cantidad_de_ejes),sobregarga(_sobregarga){};
int getCantidadDeEjes() {
return cantidad_de_ejes;
}
** int getSobregarga() const {
return sobregarga;
}**
};
int main() {
srand(time(NULL));
int a1,c1,c2,sc,cb,ct,cde, r1, vs;
vector<string> Placas={"A1R 112","F5U-597","A1A-004","D5B-193","EUA-123","A8D-457","FCD-784","F0X-694","SLA-249","EBD-608",};
vector<Base*> Vehiculos;
for (int i=0;i<10;i++){
r1=rand()%3;
vs=rand()%Placas.size();
a1=rand()%22+2000;
c1=rand()%10;
c2=rand()%10;
cb=rand()%10;
ct=rand()%3;
cde=rand()%4+3;
sc=rand()%10;
A* carro=new A(Placas.at(vs),a1,c1,cb,ct);
Vehiculos.push_back(carro);
B* moto=new B(Placas.at(vs),a1,c2);
Vehiculos.push_back(moto);
** C* camion=new C(Placas.at(vs),a1,cde,sc);
Vehiculos.push_back(camion);**
}
**Vehiculos.at(0)->getSobrecarga;**
return 0;
}
Bold parts are the vector trying to access that method, the method itself and how I create the object using dynamic objects
Note: it is usually better to expand the base class with virtual functions so that no one needs to know exactly what type is being referenced. If the children are so different that a common interface is not possible, inheritance is probably not the right solution.
If you're being forced to do this for a course, there are two changes you need to make. The base class needs to have virtual methods to be polymorphic. It just so happens it needs a virtual destructor in order for the derived classes to be destroyed correctly from a reference to Base.
class Base
{
protected:
string placa;
int ano_de_registro;
public:
Base()
{
}
Base(string _placa, int _ano_de_registro) :
placa(_placa), ano_de_registro(_ano_de_registro)
{
}
virtual ~Base() = default; //Addition
const string& getPlaca() const
{
return placa;
}
int getAnoDeRegistro() const
{
return ano_de_registro;
}
};
The second change is using dynamic_cast.
Vehiculos.at(0)->getSobrecarga;
becomes (I've also corrected a few omissions)
C* example = dynamic_cast<C*>(Vehiculos.at(2)); // get a C from the vector
if (example) // test for non-null to make sure we did indeed get a C
{
example->getSobregarga(); // do the deed.
}

Is it a necessary trade-off that using smart pointers requires my class to be publicly instantiable?

I have a base product class with a few private members and a public getter that derived classes inherit. I would like to disqualify instantiation, since the class is intended for use with an abstract factory. I thought protected con/destructors might work, however, this breaks my smart pointers. Friending seems like a useful disaster. Is there a well-known solution to this, or should I resign myself to the fact that any client who has the factory injected must also know enough to instantiate the base product?
class Product
{
private:
char type_name;
char size_name;
public:
Product(char, char);
virtual ~Product() {}
void Print();
};
Use a token key.
private:
Product(char, char);
struct key_t{explicit key_t(int){}};
static key_t key(){return key_t(0);}
public:
Product(key_t, char a, char b):Product(a,b){}
static std::shared_ptr<Product> make_shared(char a, char b){ return std::make_shared<Product>(key(),a,b); }
anyone with a Product::key_t can construct a Product without being a friend. And without the key, you cannot.
This lets Product pass creation-rights as a value.
Smart pointers with configurable destroy code can use similar techniques. But I'd just make the destructor public.
Your static member function, or friend function, which is the factory should have no problem with calling protected constructors and returning a smart pointer. Generally plan to return a std::unique_ptr<BaseClass> which can be converted into a std::shared_ptr if the caller wants that instead.
Make the virtual destructor public.
Update: Don't bother making the factory a friend. You only need to prevent the construction of the base and intermediate classes. Make them effectively hidden and private by hiding the implementation classes in their own source file. Or an anonymous namespace I suppose.
Here have some code of how I would do it:
#include <iostream>
#include <memory>
#include <string>
// ITest is the only class any other code file should ever see.
class ITest {
protected:
ITest() = default;
public:
virtual ~ITest() = 0;
virtual int getX() const = 0;
virtual int getY() const = 0;
};
// Destructors must always have an implementation even if they are pure virtual.
ITest::~ITest() {}
std::ostream &operator<<(std::ostream &os, const ITest &x) {
return os << '[' << x.getX() << ',' << x.getY() << ']';
}
// Declaration of constructTest factory function.
// Its definition should be hidden in a cpp file.
std::unique_ptr<ITest> constructTest(int x);
// The main function does not need to know anything except the ITest interface
// class and the constructTest function declaration.
int main(int argc, char *argv[]) {
int val = 0;
if (argc > 1)
val = std::stoi(argv[1]);
auto p = constructTest(val);
std::cout << *p << std::endl;
}
// These classes should be defined in a private header file or in a cpp file.
// Should not be visible to any other code. It has no business knowing.
// Hiding all of this implementation is sort of the point of abstract interface
// classes and factory function declarations.
class TestBase : public ITest {
private:
int x = 0;
int y = 0;
protected:
TestBase(int x = 0, int y = 0) : x(x), y(y){};
public:
int getX() const override { return x; }
int getY() const override { return y; }
};
class TestA final : public TestBase {
public:
TestA() = default;
};
class TestB final : public TestBase {
public:
TestB(int x, int y) : TestBase(x, y) {}
int getX() const override { return -TestBase::getX(); }
};
std::unique_ptr<ITest> constructTest(int x) {
// make_unique is c++14.
// For C++11 use std::unique_ptr<ITest>(new TestB(x, x)
if (x) {
return std::make_unique<TestB>(x, x);
// return std::unique_ptr<ITest>(new TestB(x, x));
}
return std::make_unique<TestA>();
}
The answer was to make the destructor a pure virtual AND to implement it with an empty body. That empty implementation is where I got tripped up. Print() doesn't need to be static.
Product.hpp
#include <memory>
class Product {
public:
virtual ~Product() = 0;
void Print();
protected:
char type_name{};
char size_name{};
private:
};
Product.cpp
#include "Product.hpp"
Product::~Product() {}
void Product::Print() {
//Print p
}

C++ static member modifiers for subclasses

Consider the following code:
#include <stdio.h>
#include <iostream>
/// Header-file
class Base {
public:
virtual void do_something() const =0;
int GetAttrib () const {return constattribute_;};
static const int constattribute_;
};
typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base
class DerivedA : public Base {
// static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives
void do_something() const {};
};
class DerivedB : public Base {
// static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives
void do_something() const {};
};
/// CC-file
using namespace std;
const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB
int main(void) {
Derived_Ptr derivedA = new DerivedA();
Derived_Ptr derivedB = new DerivedB();
cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;
return 0;
};
The intend being that i have some abstract interface (Base) which defines also a variable, which should be present for all derived classes, and is retrievable. All flavours of subclasses should be forced to/able to redefine their specific value for this variable, at best during class declaration (the values are known at the time the class is declared after all).
I want to achieve code, not altering the main()-program so that the output is '12' and not as of now (uncommenting current lines in the code) '00' (Doing so shadows the fields from base class).
I tried to look into the matter, and there are different paths for solutions, many of which however go contrary to my intuition:
1. Some follow the CRTP pattern, which is however impossible if I want to address my subclasses by their base-ptr in main.
2. Other solutions require to virtualize the 'GetAttrib()' function for every derived instance., which is cumbersome, and action of modifying the attribute is masked within a function definition.
3. A third possibility is to remove the static pattern and have the 'constattribute_' field as a regular member, which however forces me to drag it through all constructors as a parameter.
I am quite sure that there must be some smarter way to do this. Any hints are appreciated.
Using CRTP may get you what you want, assuming you don't have to access GetAttr() through Base* and can leave without constattribute_ in Base itself. Just follow the rule that every programming problem can be solved by entering another level of indirection, which I did below:
class Base {
public:
virtual void do_something() const = 0;
virtual ~Base() // should define it as you are using Base*
{
}
};
typedef Base* Derived_Ptr;
template<class T>
class BaseConstAttr : public Base
{
public:
int GetAttrib () const
{
return(constattribute_);
};
static const int constattribute_;
};
class DerivedA : public BaseConstAttr<DerivedA>
{
public:
void do_something() const
{
};
};
class DerivedB : public BaseConstAttr<DerivedB>
{
public:
void do_something() const
{
};
};
template<> const int BaseConstAttr<DerivedA>::constattribute_(1);
template<> const int BaseConstAttr<DerivedB>::constattribute_(2);
If you need GettAttr from top to bottom of the inheritance tree you can modify the above code a bit, but this will cost you making GetAttr virtual (but still one implementation only):
class Base {
public:
virtual void do_something() const = 0;
virtual int GetAttrib () const = 0;
virtual ~Base() // should define it as you are using Base*
{
}
};
typedef Base* Derived_Ptr;
template<class T>
class BaseConstAttr : public Base
{
public:
int GetAttrib () const
{
return(constattribute_);
};
static const int constattribute_;
};
class DerivedA : public BaseConstAttr<DerivedA>
{
public:
void do_something() const
{
};
};
class DerivedB : public BaseConstAttr<DerivedB>
{
public:
void do_something() const
{
};
};
template<> const int BaseConstAttr<DerivedA>::constattribute_(1);
template<> const int BaseConstAttr<DerivedB>::constattribute_(2);
Please note that I don't know how well (or bad) it will behave with deep inheritance tree (ie. when inheriting from DerivedA and/or DerivedB). In this case I would probably remove BaseConstAttr from inheritance tree right below Base and would try to inject it between most derived class and its predecessor or use multiple inheritance.
What you are requesting requires virtual dispatch somewhere, because you don't know the type of the object you are dealing with until runtime. The purpose of virtual dispatch is to solve exactly the problem you are facing.
The simplest solution is what you have given as number 2: make GetAttrib() virtual, and implement it on each derived class where you introduce a shadowing constattribute_.
static variable in base class is single instance hence it will be reflected same in derived class.
You can make same static member variable in derived class with specific different value you want. Now make getter member function of static variable in Base class as virtual and overload it in derived class which returns is static instance value.
I have update your code to work it, please check ..
#include <iostream>
using namespace std;
class Base {
public:
static const int constattribute_;
virtual void do_something() const =0;
virtual int GetAttrib () const {return constattribute_;};
};
typedef Base* Derived_Ptr; //<< adress derived classes by their base-class ptr; so no templates for Base
class DerivedA : public Base {
static const int constattribute_; //<< change this static attribute for all DerivedA class instances and their derivatives
void do_something() const {};
int GetAttrib () const {return constattribute_;};
};
class DerivedB : public Base {
static const int constattribute_; //<< change this static attribute for all DerivedB class instances and their derivatives
void do_something() const {};
int GetAttrib () const {return constattribute_;};
};
const int Base::constattribute_(0);
const int DerivedA::constattribute_(1); //<<error: no such variable 'constattribute' in class DerivedA
const int DerivedB::constattribute_(2); //<<error: no such variable 'constattribute' in class DerivedB
int main(void) {
Derived_Ptr derivedA = new DerivedA();
Derived_Ptr derivedB = new DerivedB();
cout << derivedA->GetAttrib() << derivedB->GetAttrib() <<endl;
return 0;
};
You should get desired output.
Note : Remember all member variables and func in derived class are private.

Virtual function definition in base class gives error

I had written a set of classes to check composition pattern.
Here is my code:
#include <iostream>
#include <string>
#include <list>
#include "InvalidCompositeException.h"
using namespace std;
class Composite;
class Component {
public:
Component() {}
virtual ~Component() {}
virtual string getName() = 0;
virtual int getNetPrice() = 0;
virtual Composite* getComposite() {
try {
throw myEx;
} catch (InvalidCompositeException& e) {
cout<<"Exception: "<<e.what();
}
return 0;
}
**virtual void add(Component* c);
virtual void remove(Component* c);**
private:
};
class Composite : public Component {
public:
Composite():mChildList(new list<Component*>()) {}
virtual ~Composite() {
mChildList->clear();
delete mChildList;
}
virtual string getName() {return "Composite";}
virtual int getNetPrice() {
list<Component*>::iterator i;
int sum = 0;
for(i=mChildList->begin(); i!= mChildList->end(); ++i) {
sum = sum + (*i)->getNetPrice();
}
return sum;
}
virtual void add(Component* c) {
mChildList->push_back(c);
}
virtual void remove(Component* c) {
mChildList->remove(c);
}
private:
list<Component*>* mChildList;
};
class Container: public Composite {
public:
Container() {}
virtual ~Container() {}
string getName() {
cout<<"container"<<endl;
return "container";
}
};
class Line: public Component {
public:
Line(): mNetPrice(50) {}
~Line() {};
int getNetPrice() { return mNetPrice; }
string getName() {
cout<<"line"<<endl;
return "line";
}
private:
int mNetPrice;
};
class Text: public Component {
public:
Text(): mNetPrice(100) {}
~Text() {};
int getNetPrice() { return mNetPrice; }
string getName() {
cout<<"Text"<<endl;
return "Text";
}
private:
int mNetPrice;
};
int main(void) {
Container* c = new Container();
Line* l = new Line();
Text* t = new Text();
c->add(l);
c->add(l);
c->add(t);
cout<<"total price for c is "<<c->getNetPrice();
l->getComposite();
delete t;
delete l;
delete c;
return EXIT_SUCCESS;
}
My code runs fine except when I add those bold lines in my parent class that i receive errors
undefined reference to `vtable for Component' // on this line virtual ~Component() {}
undefined reference to `Component::add(Component*)'
undefined reference to `Component::remove(Component*)'
I have not define virtual functions to be pure. Then why do I receive those errors even if i don't define them in Line and Text Classes. If I dont add those bold declarations my code works fine. And secondly why error on destructor?
Non-pure virtual functions need to have a definition, even if they are never called (so that the linker has something to put in the vtable). Simply add =0 to make your class abstract, or provide empty definitions.
The error with the destructor is a little more involved, but basically the compiler needs to decide in which object file to place the vtable for your polymophic class -- it usually does this wherever the first non-pure, non-inline virtual function is defined (with more complicated rules where there are no such functions). In this case, you're declaring two out-of-line virtual functions, but never defining them, so the compiler never writes the vtable into an object file.
If there's no implementation in the base class, you need to make them abstract with the =0 in the virtual function declaration. Otherwise, the virtual function table for the base class will try to find bodies - without the =0, it figures they must exist, and that will end up pointing at nothing, causing the linker error.
The destructor error is the same thing - it needs that complete table to find the virtual dtor and the table isn't complete.
Consider:
class foo
{
public:
void doit();
};
foo f;
f.doit(); // linker error, doit isn't defined!
What do you think happens if void doit() becomes virtual doit()? Nothing, same error as you have now. However virtual void doit() = 0 by making it pure will resolve the error. A virtual function is like any other, it must have an implementation.

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.