I am trying to solve this problem but I don't know how to make conversion from interface class to my child class. Basicly, I am trying to make array of Vehicle pointers and elements of array to be child classes pointers, then pass element by element to Counter class method which will calculate value of total passengers, but I get compiler error:
invalid conversion from 'oss:Vehicle*' to 'oss::Bike*' [-fPermissive]
Here is my code:
Vehicle.h
using namespace std;
namespace oss{
class Vehicle
{
public:
virtual string type() = 0;
virtual unsigned passengers() = 0;
virtual ~Vehicle();
};
class Land_vehicle : public Vehicle{
protected:
string typeOfVehicle;
unsigned numberOfPassengers;
public:
Land_vehicle();
string type();
};
class Bike : public Land_vehicle{
public:
Bike();
unsigned passengers();
};
class Counter{
private:
int totalPassengers;
public:
Counter();
void add(Bike*b);
int total();
};
Vehicle.cpp
using namespace oss;
Vehicle::~Vehicle(){};
Land_vehicle::Land_vehicle(){typeOfVehicle = "Land";}
string Land_vehicle::type(){return typeOfVehicle;}
Bike::Bike(){numberOfPassengers = 1;}
unsigned Bike::passengers(){return numberOfPassengers;}
Counter::Counter(){totalPassengers = 0;}
void Counter::add(Bike b){
cout <<"inside add bike"<<endl;
totalPassengers += b.passengers();
}
int Counter::total(){return totalPassengers;}
Main.cpp
using namespace std;
using namespace oss;
int main()
{
Counter c;
Vehicle* v[] = {new Bike};
size_t sz = sizeof v/sizeof v[0];
for (unsigned i = 0; i < sz; ++i)
c.add(v[i]);
std::cout << "Total: " << c.total() << " passengers!" << std::endl;
for (unsigned i = 0; i < sz; ++i)
delete v[i];
return 0;
}
According to your classes, every Bike and every Car are Vehicules. THis is why, whenever you need a Vehicle*, you can use as well a Bike*or aCar*`.
You make use of this in your assignment:
Vehicle* v[] = {new Bike}; // yes a Bike* can be converted to a Vehicle*
However the reverse relation is not true. Not every Vehicle is necessary a Bike. This is why you can't just use a Vehicle* when you need a Bike*. To do the reverse condition you first have to check that the Vehicle you're working with is indeed a Bike, and if it's the case you can use casting.
Fortunately, your classes are polymorphic (due to the virtual functions). So you have to use a dynamic_cast() to convert from parent (base) pointer to child (derived) pointer. But take care to check that the conversion succeeds (i.e. casted pointer isn't null).
What's wrong here ?
You experience this and related problems, when you try to add a vehicle to your counter:
c.add(v[i]); // v[i] is a pointer to a vehicle, but which one
In fact there are several problems with your Counter::add() :
first, you have a plain object as argument, not a pointer. This means that you'd need to dereference the pointer with c.add(*v[i]). But the overload require that you tell at compile time which type of object it is (i.e. there's no add(Vehicle), and if there would be one, you'd suffer from object slicing)
then, if you'd use a pointer instead of a plain object, you could use casting: c.add(dynamic_cast<Bike*>(v[i]);
finally, you'll realize that even with casting, you have a problem: in your example you vow that there's only a bike in your array. But in real code, you couldn't now for sure.
First work around
Now putting this together, here is how to modify your loop to add to the counter only bikes:
for (unsigned i = 0; i < sz; ++i) {
if (dynamic_cast<Bike*>(v[i]))
c.add(dynamic_cast<Bike*>(v[i]));
}
THis suppose to change the signature of add to:
void Counter::add(Bike* b){
cout <<"inside add bike"<<endl;
totalPassengers += b->passengers();
}
Here a live demo
And a solution
If you have polymorphic classes, it's a pitty not to benefit from polymorphism:
class Counter {
int totalPassengers;
public:
Counter();
void add(Vehicle* b);
int total();
};
And the implementation of the redesigned function:
void Counter::add(Vehicle* b){
totalPassengers += b->passengers();
}
And this will work whatever the number of classes you derive from vehicle ! No longer need to add dozens of similar overloads of the same function.
Online demo
Related
I want to loop through an array of pointers to an abstract class to find an "empty" slot, that is to check whether an element points to an object of a derived class or not. My approach is to create the array and set each element to nullptr. Then, I can check if the element is nullptr.
This works, but is there a better way?
Edit: Can I check for the first "empty" element in the array of pointers to an abstract class (in which derived classes will periodically be constructed and pointed to by the array, rendering that element not "empty"), without assigning each element to nullptr upon setting up the array and then checking for nullptr as a way to check if the element is "empty"? In other words, can I directly check whether the element points to a constructed base class or not?
Cat** catArray = new Cat*[200];
for(int i = 0; i < 200; i++){
catArray[i] = nullptr;
}
for(int i = 0; i < 200; i++){
if(catArray[i] == nullptr){ //edited, was typo as "!="
AddRealCat(...);
break;
}
}
I wonder if there's an easier way to do this, to check whether an element in an array of pointers to an abstract class points to an object of a derived class or is just an abstract pointer, without setting the element to nullptr. Like, is there a bool IsObject(ObjectType* ptr) or something in the standard library?
And, I wonder if setting each element to nullptr poses any potential problems, other than the computing cost of looping through the array and setting the elements to nullptr.
You would have to use dynamic_cast to cast a base class pointer to a derived class pointer. dynamic_cast performs type safe down casting.
If the result of dynamic_cast is not nullptr then the cast has been successful. Otherwise no derived class pointer can be obtained from the pointer.
You would have to do like this:
Cat *pCat = dynamic_cast<Cat*>(catArray[i]);
if (pCat)
{
AddRealCat(...);
break;
}
where catArray is an array of base class pointers.
Update
I think there's an error with creating an array of real cat objects:
for(int i = 0; i < 200; i++){
if(catArray[i] != nullptr){
AddRealCat(...);
break;
}
}
Surely you need to check == nullptr since you initialising all array elements to nullptr? I think you need to make the following change:
for(int i = 0; i < 200; i++){
if(catArray[i] == nullptr){
catArray[i] = new RealCat();
break;
}
}
I guess the real easier way to do that other using dynamic_cast is using std::vector instead of a raw pointer.
Sample code
#include <string>
#include <iostream>
#include <vector>
struct Cat{
virtual ~Cat() = default;
virtual void meow() const = 0;
};
struct Meow : Cat{
void meow() const override{ std::cout << "meow" << std::endl; }
};
int main()
{
std::vector<Cat*> vec{100};
vec[1] = new Meow();
for(auto c : vec){
if(auto m = dynamic_cast<Meow*>(c)){
m->meow();
}
}
// don't forget to release memory
for(auto c : vec){
delete c;
}
}
Live Example
Modern version, using smart pointers.
#include <string>
#include <iostream>
#include <vector>
#include <memory>
struct Cat{
virtual ~Cat() = default;
virtual void meow() const = 0;
};
struct Meow : Cat{
void meow() const override{ std::cout << "meow" << std::endl; }
};
int main()
{
std::vector<std::unique_ptr<Cat>> vec{100};
vec[1] = std::make_unique<Meow>();
for(auto&& c : vec){
if(auto m = dynamic_cast<Meow*>(c.get())){
m->meow();
}
}
// you don't need to manually clear the memory.
}
Live Example
I have code like this:
class Human
{
protected:
int age;
std::string sex;
public:
virtual void speak() = 0;
};
class Child:public Human
{
public:
void speak(){std::cout << "I am Child\n";}
};
class Man:public Human
{
public:
void speak(){std::cout << "I am Man\n";}
};
class Woman:public Human
{
public:
void speak(){std::cout << "I am Woman\n";}
};
(don't know, std::shared_ptr<Human> maybe?) operator*(std::shared_ptr<Child> &b, int x)
{
b->setAge(b->getAge()+x);
if(b->getAge()>18 && b->getSex()=="Man")
{
return (i want b to become std::shared_ptr<Man>)
}
if(b->getAge()>18 && b->getSex()=="Woman")
{
return (here I want b to become std::shared_ptr<Woman>);
}
return;
}
int main(){
auto x = std::make_shared<Child>;
x*19;
}
I know it seems odd, but it's the simplest case i can think of, without having to write down all code i'm struggling with rn. Could someone explain, what type should overload be and how to change shared_ptr type, knowing they derive from same parent?
Objects cannot change type. A Child object will always be a Child object. What you can do is create a new object with the properties you want and return that:
std::shared_ptr<Human> operator*(std::shared_ptr<Human> b, int x)
{
b->setAge(b->getAge()+x);
if(b->getAge()>18 && b->getSex()=="Man") {
return std::make_shared<Man>(b->getAge());
} else if(b->getAge()>18 && b->getSex()=="Woman") {
return std::make_shared<Woman>(b->getAge());
} else {
return b;
}
}
int main(){
std::shared_ptr<Human> x = std::make_shared<Child>;
x = x*19;
}
This doesn't seem like a good design though. A Human's status as a child or adult would be better represented as an attribute of the object or by a function that checks if age is greater than 18.
You cannot make the type T<Derived> inherit from T<Base> because C++ templates do not support covariance. To do so would be unsafe for certain types, such as mutable references to containers. (Imagine taking a reference to std::vector<Cat> as std::vector<Animal>& and pushing back a dog!)
(I would make this answer a comment, but I don't have comment abilities.)
Update:
You can write a non-template wrapper that handles heap data:
class Wrapper
{
public:
Wrapper(Base* b) : raw(b) {}
~Wrapper() { delete raw; }
Base& get() { return *base; }
private:
Base* raw;
}
Of course, in your example, you use std::shared_ptr and not std::unique_ptr. You would have to handle reference counting instead of simply deleting the data in the destructor, but the technique of keeping an internal raw pointer still stands.
Update 2:
The above code could be used as is to provide a level of indirection, such that all classes that inherit from the base class may be held in the same type, without writing your own reference counter:
std::shared_ptr<Wrapper>
This solution may be seen as similar to doing std::shared_ptr<Base*>, except that the latter solution would leak memory.
I have my main.cpp like this:
#include <iostream>
#include "curve1.h"
#include "curve2.h"
using namespace std;
int main()
{
Curve1 curve1Obj;
Curve2 curve2Obj;
curve1Obj.enterScores();
curve1Obj.calcAverage();
curve1Obj.output();
curve1Obj.curve();
curve1Obj.output(curve1Obj.new_getAverage1(), curve1Obj.new_getScore1());
curve2Obj.curve();
return 0;
}
Base class Score has two derived classes Curve1 and Curve2. There are two curve() functions, one is in Curve1 and other in Curve2 classes. getSize() returns the value of iSize.
My base class header score.h looks like this:
#ifndef SCORE_H
#define SCORE_H
class Score
{
private:
int *ipScore;
float fAverage;
int iSize;
public:
Score(
void enterScores();
void calcAverage();
void output();
void output(float, int*);
void setSize();
int getSize();
void setScore();
int *getScore();
float getAverage();
};
#endif
You can see that I have used curve1Obj to enter scores, calculate average and output. So if I call getSize() function with cuve1Obj, it gives the right size that I took from user in enterScores() function. Also the result is same if I call getSize() in score.cpp definition file in any of the functions (obviously).
.....
The problem is when I call curve() function of Curve2 class in main (line 23) with the object curve2Obj, it creates a new set of ipScore, fAverage and iSize (i think?) with garbage values. So when I call getSize() in curve() definition in curve2.cpp, it outputs the garbage.
.....
How can I cause it to return the old values that are set in curve1.cpp?
Here is my curve2.cpp
#include <iostream>
#include "curve2.h"
using namespace std;
void Curve2::curve()
{
cout << "getSize() returns: " << getSize() << endl; // out comes the garbage
}
Can I use a function to simply put values from old to new variables? If yes then how?
Well, basically your problem can't be easily solved the way it is.
Like you said:
1 - Don't use constructors of any type.
2 - Don't use vectors.
3 - Using dynamic new and delete etc. etc.
Use the constructors or stick with what G. Samaras and Richard Hodges said. You can only solve this that way.
There is limited information available here but I would say that your Score constructor has not initialised ipScore or iSize.
If you are hell-bent on using a pointer to a dynamically allocated array of ints for your score then at least null out the pointer in the constructor and test for null in the average function (i.e. no scores yet).
Better yet... use a std::vector of int for your scores.
Why are people still using new and delete? What the hell are they teaching in schools?
What I think you want is this:
#include <vector>
class Score {
public:
Score()
: _scores()
, _average(0)
{ }
void calcAverage() {
double total = 0;
if(auto s = _scores.size() > 0) {
for (const auto& v : _scores)
total += v;
total /= s;
}
_average = total;
}
virtual void curve() = 0;
protected:
// one of the few correct uses of 'protected' - giving limited access to data as interface to derived classes
const std::vector<double>& scores() const {
return _scores;
}
// or
std::vector<double> copyScores() const {
return _scores;
}
private:
// use doubles since you'll be doing floating point arithmetic
std::vector<double> _scores;
double _average;
};
class Curve1 : public Score {
public:
virtual void curve() override {
// custom curve function here
// written in terms of scores() or copyScores() if you want to make changes to the array
}
};
class Curve2 : public Score {
public:
virtual void curve() override {
// custom curve function here
// written in terms of scores();
}
};
You need to understand inheritance. Curve1 inherits from Score. Curve2 inherits from Score.
Now see this example:
#include <iostream>
class Base {
int x;
};
class A : public Base {
int a;
public:
void set_a(int arg) {
a = arg;
}
int get_a() {
return a;
}
};
class B : public Base {
int b;
public:
void set_b(int arg) {
b = arg;
}
int get_b() {
return b;
}
};
int main() {
A a_object;
a_object.set_a(4);
B b_object;
b_object.set_b(a_object.get_a());
std::cout << "a of a_object = " << a_object.get_a() << "\n";
std::cout << "b of b_object = " << b_object.get_b() << "\n";
return 0;
}
class A, has as members x and a. Class B has as members x and b.
When I create an instance of class A, I will two data members created internally, x and a.
When I create an instance of class A, I will two data members created internally, x and b.
But, the first x and the second are DIFFERENT. They are a different cell in the memory!
something like this:
class Score {
public:
Score()
: _scores(0)
, _size(0)
, _average(0)
{ }
// copy constructor
Score(const Score& rhs)
: _scores( new double[rhs._size] )
, _size(rhs._size)
, _average(rhs._average)
{
if (_size) {
for(int i = 0 ; i < _size ; ++i) {
_scores[i] = rhs._scores[i];
}
}
}
// ... and if copy constructor then always a copy operator
Score& operator=(const Score& rhs) {
// assignment in terms of copy constructor - don't repeat yourself
Score tmp(rhs);
swap(tmp);
return *this;
}
// pre c++11 we make our own swap.
// post c++11 we would make non-throwing move constructor and move-assignment operator
void swap(Score& rhs) {
// std::swap is guaranteed not to throw
std::swap(_scores, rhs._scores);
std::swap(_size, rhs._size);
std::swap(_average, rhs._average);
}
~Score()
{
delete[] _scores;
}
void calcAverage() {
double total = 0;
if(_size > 0) {
for (int i = 0 ; i < _size ; ++i)
total += _scores[i];
total /= _size;
}
_average = total;
}
virtual void curve() {};
private:
// use doubles since you'll be doing floating point arithmetic
double * _scores;
int _size;
double _average;
};
// rmember to override the copy operators and assignment operators of derived classes
// remember to call the base class's operator
I am making a toy programming language in c++, but i have run into a problem. I have noticed that in c++ a stack can only store one type of data. I was wondering if there was an easy way to fix this problem, such as by storing in the stack a byte array of each object. I was wondering if anyone knows how the jvm overcomes this issue. The types i would need to store on the stack would be char, short, int, float, double, strings, arrays, and references to objects. I understand that the jvm stack might be more of an abstraction, but if it is i would still like to know how they have accomplished it. If it makes any difference, i am only planning to target windows computers.
You know C++ has support for inheritance and polymorphism, right? A far easier way to do this is to derive all your tokens from a common base class, and make a stack of Base * objects, for instance:
#include <iostream>
#include <string>
#include <stack>
#include <memory>
class base {
public:
virtual void print_token() = 0;
virtual ~base() {}
};
class token_a : public base {
public:
token_a(int n) : n(n) {}
virtual void print_token() { std::cout << n << std::endl; }
private:
int n;
};
class token_b : public base {
public:
token_b(std::string s) : s(s) {}
virtual void print_token() { std::cout << s << std::endl; }
private:
std::string s;
};
int main(void) {
std::stack<std::shared_ptr<base> > my_stack;
my_stack.push(std::shared_ptr<base>(new token_a(5)));
my_stack.push(std::shared_ptr<base>(new token_b("a word")));
for ( int i = 0; i < 2; ++i ) {
std::shared_ptr<base> pb = my_stack.top();
pb->print_token();
my_stack.pop();
}
return 0;
}
outputs:
paul#local:~/src/cpp/scratch$ ./stack
a word
5
paul#local:~/src/cpp/scratch$
The way I have solved this problem (in C, for a lisp interpretr, about 25 years ago, but same idea applies today) is to have a struct with a type and a union inside it:
struct Data // or class
{
enum kind { floatkind, intkind, stringkind, refkind };
Kind kind;
union
{
double f;
int i;
std::string s;
Data* r; // reference, can't use Data &r without heavy trickery.
} u;
Data(double d) { kind = floatkind; u.f = d; }
Data(int i) { kind = intkind; u.i = i; }
...
}
std::stack<Data> st;
st.push(Data(42));
st.push(Data(3.14));
Just a guess, but the jvm probably treats everything as an object, so the stack is simply a collection of objects.
You can do the same, if you create a base data object class and derive all your supported data types from it.
Consider the following code snippet:
struct Base { virtual void func() { } };
struct Derived1 : Base { void func() override { print("1"); } };
struct Derived2 : Base { void func() override { print("2"); } };
class Manager {
std::vector<std::unique_ptr<Base>> items;
public:
template<class T> void add() { items.emplace_back(new T); }
void funcAll() { for(auto& i : items) i->func(); }
};
int main() {
Manager m;
m.add<Derived1>();
m.add<Derived2>();
m.funcAll(); // prints "1" and "2"
};
I'm using virtual dispatch in order to call the correct override method from a std::vector of polymorphic objects.
However, I know what type the polymorphic objects are, since I specify that in Manager::add<T>.
My idea was to avoid a virtual call by taking the address of the member function T::func() and directly storing it somewhere. However that's impossible, since I would need to store it as void* and cast it back in Manager::funcAll(), but I do not have type information at that moment.
My question is: it seems that in this situation I have more information than usual for polymorphism (the user specifies the derived type T in Manager::add<T>) - is there any way I can use this type information to prevent a seemingly unneeded virtual call? (An user should be able to create its own classes that derive from Base in its code, however.)
However, I know what type the polymorphic objects are, since I specify that in Manager::add<T>.
No you don't. Within add you know the type of the object that's being added; but you can add objects of different types, as you do in your example. There's no way for funcAll to statically determine the types of the elements unless you parametrise Manager to only handle one type.
If you did know the type, then you could call the function non-virtually:
i->T::func();
But, to reiterate, you can't determine the type statically here.
If I understand well, you want your add method, which is getting the class of the object, to store the right function in your vector depending on that object class.
Your vector just contains functions, no more information about the objects.
You kind of want to "solve" the virtual call before it is invoked.
This is maybe interesting in the following case: the function is then called a lot of times, because you don't have the overhead of solving the virtual each time.
So you may want to use a similar process than what "virtual" does, using a "virtual table".
The implementation of virtual is done at low level, so pretty fast compared to whatever you will come up with, so again, the functions should be invoked a LOT of times before it gets interesting.
One trick that can sometimes help in this kind of situation is to sort the vector by type (you should be able to use the knowledge of the type available in the add() function to enforce this) if the order of elements doesn't otherwise matter. If you are mostly going to be iterating over the vector in order calling a virtual function this will help the CPU's branch predictor predict the target of the call. Alternatively you can maintain separate vectors for each type in your manager and iterate over them in turn which has a similar effect.
Your compiler's optimizer can also help you with this kind of code, particularly if it supports Profile Guided Optimization (POGO). Compilers can de-virtualize calls in certain situations, or with POGO can do things in the generated assembly to help the CPU's branch predictor, like test for the most common types and perform a direct call for those with a fallback to an indirect call for the less common types.
Here's the results of a test program that illustrates the performance benefits of sorting by type, Manager is your version, Manager2 maintains a hash table of vectors indexed by typeid:
Derived1::count = 50043000, Derived2::count = 49957000
class Manager::funcAll took 714ms
Derived1::count = 50043000, Derived2::count = 49957000
class Manager2::funcAll took 274ms
Derived1::count = 50043000, Derived2::count = 49957000
class Manager2::funcAll took 273ms
Derived1::count = 50043000, Derived2::count = 49957000
class Manager::funcAll took 714ms
Test code:
#include <iostream>
#include <vector>
#include <memory>
#include <random>
#include <unordered_map>
#include <typeindex>
#include <chrono>
using namespace std;
using namespace std::chrono;
static const int instanceCount = 100000;
static const int funcAllIterations = 1000;
static const int numTypes = 2;
struct Base { virtual void func() = 0; };
struct Derived1 : Base { static int count; void func() override { ++count; } };
int Derived1::count = 0;
struct Derived2 : Base { static int count; void func() override { ++count; } };
int Derived2::count = 0;
class Manager {
vector<unique_ptr<Base>> items;
public:
template<class T> void add() { items.emplace_back(new T); }
void funcAll() { for (auto& i : items) i->func(); }
};
class Manager2 {
unordered_map<type_index, vector<unique_ptr<Base>>> items;
public:
template<class T> void add() { items[type_index(typeid(T))].push_back(make_unique<T>()); }
void funcAll() {
for (const auto& type : items) {
for (auto& i : type.second) {
i->func();
}
}
}
};
template<typename Man>
void Test() {
mt19937 engine;
uniform_int_distribution<int> d(0, numTypes - 1);
Derived1::count = 0;
Derived2::count = 0;
Man man;
for (auto i = 0; i < instanceCount; ++i) {
switch (d(engine)) {
case 0: man.add<Derived1>(); break;
case 1: man.add<Derived2>(); break;
}
}
auto startTime = high_resolution_clock::now();
for (auto i = 0; i < funcAllIterations; ++i) {
man.funcAll();
}
auto endTime = high_resolution_clock::now();
cout << "Derived1::count = " << Derived1::count << ", Derived2::count = " << Derived2::count << "\n"
<< typeid(Man).name() << "::funcAll took " << duration_cast<milliseconds>(endTime - startTime).count() << "ms" << endl;
}
int main() {
Test<Manager>();
Test<Manager2>();
Test<Manager2>();
Test<Manager>();
}