no viable overloaded '=' error, what may cause this? - c++

Note: I have uploaded my code here: https://onlinegdb.com/r1P8APG0I you can run it and reproduce the bug.
I wrote an abstract Character class with is inherited by many classes like Soldier and Medic. also, I have a Game class which has:
mtm::Dimensions dimensions;
std::vector<std::shared_ptr<Character>> board;
Important Note: I can't change the code that's written above, so please consider that.
I need to write a copy c'tor for this class Which makes a copy that isn't related at all to the previous one after the call is finished, So I wrote:
Game::Game(const Game &other):dimensions(other.dimensions){
int board_size = dimensions.getRow() * dimensions.getCol();
for (int i = 0; i < board_size; ++i) {
Character* copy = other.board[i]->clone();
board[i]=*copy;
}
}
But I'm getting an error saying:
error: no viable overloaded '=' board[i]=*copy;
What does this mean and how may I fix it?
You may need the following implementation of clone over Medic class which inherits Character
Character * Medic::clone() const {
return new Medic(*this);
}
Update: I tried writing =copy instead of =*copy but got exactly the same error.

You are dereferencing a pointer here
board[i]=*copy;
If instead you are trying to construct a std::shared_ptr then create one using your raw pointer
board[i] = std::shared_ptr<Character>(copy);
which more concisely is just
board[i] = std::shared_ptr<Character>(other.board[i]->clone());

Related

Downcasting trouble

This is my first experience with downcasting in C++ and I just can't understand the problem.
AInstruction and CInstruction inherit from AssemblerInstruction.
Parser takes the info in its ctor and creates one of those derived instruction types for its mInstruction member (accessed by getInstruction). In the program, a method of the base AssemblerInstruction class is used, for happy polymorphism.
But when I want to test that the Parser has created the correct instruction, I need to query the derived instruction members, which means I need to downcast parser.getInstruction() to an AInstruction or CInstruction.
As far as I can tell this needs to be done using a bunch of pointers and references. This is how I can get the code to compile:
TEST(ParserA, parsesBuiltInConstants)
{
AssemblerInstruction inst = Parser("#R3", 0).getInstruction();
EXPECT_EQ(inst.getInstructionType(), AssemblerInstruction::InstructionType::A);
AssemblerInstruction* i = &(inst);
AInstruction* a = dynamic_cast<AInstruction*>(i);
EXPECT_EQ(a->getLine(), "R3");
}
Running this gives this error:
unknown file: error: SEH exception with code 0xc0000005 thrown in the test body.
And stepping through the code, when the debugger is on the final line of the function, a is pointing to
0x00000000 <NULL>.
I imagine this is an instance where I don't have a full enough understanding of C++, meaning that I could be making a n00b mistake. Or maybe it's some bigger crazy problem. Help?
Update
I've been able to make this work by making mInstruction into a (dumb) pointer:
// in parser, when parsing
mInstructionPtr = new AInstruction(assemblyCode.substr(1), lineNumber);
// elsewhere in AssemblerInstruction.cpp
AssemblerInstruction* AssemblyParser::getInstructionPtr() { return mInstructionPtr; }
TEST(ParserA, parsesBuiltInConstants)
{
auto ptr = Parser("#R3", 0).getInstructionPtr();
AInstruction* a = dynamic_cast<AInstruction*>(ptr);
EXPECT_EQ(a->getLine(), "R3");
}
However I have trouble implementing it with a unique_ptr:
(I'm aware that mInstruction (non-pointer) is redundant, as are two types of pointers. I'll get rid of it later when I clean all this up)
class AssemblyParser
{
public:
AssemblyParser(std::string assemblyCode, unsigned int lineNumber);
AssemblerInstruction getInstruction();
std::unique_ptr<AssemblerInstruction> getUniqueInstructionPtr();
AssemblerInstruction* getInstructionPtr();
private:
AssemblerInstruction mInstruction;
std::unique_ptr<AssemblerInstruction> mUniqueInstructionPtr;
AssemblerInstruction* mInstructionPtr;
};
// in AssemblyParser.cpp
// in parser as in example above. this works fine.
mUniqueInstructionPtr = make_unique<AInstruction>(assemblyCode.substr(1), lineNumber);
// this doesn't compile!!!
unique_ptr<AssemblerInstruction> AssemblyParser::getUniqueInstructionPtr()
{
return mUniqueInstructionPtr;
}
In getUniqueInstructionPtr, there is a squiggle under mUniqueInstructionPtr with this error:
'std::unique_ptr<AssemblerInstruction,std::default_delete>::unique_ptr(const std::unique_ptr<AssemblerInstruction,std::default_delete> &)': attempting to reference a deleted function
What!? I haven't declared any functions as deleted or defaulted!
You can not downcast an object to something which doesn't match it's dynamic type. In your code,
AssemblerInstruction inst = Parser("#R3", 0).getInstruction();
inst has a fixed type, which is AssemblerInstruction. Downcasting it to AInstruction leads to undefined behavior - manifested as crash - because that is not what it is.
If you want your getInstruction to return a dynamically-typed object, it has to return a [smart] pointer to base class, while constructing an object of derived class. Something like that (pseudo code):
std::unique_ptr<AssemblerInstruction> getInstruction(...) {
return std::make_unique<AInstruction>(...);
}
Also, if you see yourself in need of downcasting object based on a value of a class, you are doing something wrong, as you are trying to home-brew polymorphism. Most of the times it does indicate a design flaw, and should instead be done using built-in C++ polymorphic support - namely, virtual functions.

I want to make instance with array in SystemC

I want to make instance with array in SystemC.
I want to write as follows:
module name = new module[10];
or
for(int i = 0; i < 10; i++){
module name[i]("any names")
}
However, I did this, the compiler said:
error: no matching function for call to 'module::module()'
Please tell me how to make an instance with array.
In SystemC, you can use sc_vector instead of a plain C array, see e.g.
https://standards.ieee.org/standard/1666-2011.html (Section 8.5)
https://complex.offis.de/documents/doc_details/29-scvector-and-the-ieee-p1666-2011-systemc-standard.html
SC_MODULE(top)
{
sc_vector<module> m; // e.g. class member
SC_CTOR(top)
: m("modules", 10) // constructor
{}
};

Logical operator causing compile-time error on functions called

This question might have been answered before, but searching around and using google didn't bring me there, so I'll ask.
I'm currently making a game and working on collision, however, for some reason it seems like whenever I try to compile I get a ISO C++ forbids comparison between pointer and integer
At first I thought I might have something wrong in my syntax which I checked, but wasn't able to find anything, so I just left the line of code to this:
if((getMinX() > c->getMinX()) && (getMinX() < c-getMaxX()))
I tried adding this-> or adding parenthesis, but that doesn't seem to work, however, just doing
if(this->getMinX() > c->getMinX())
seems to work fine as well as
if((5 > 3) && (5 < 10))
Is there something I'm missing?
Both objects are derived from a class called Collideable defined like this
class Collideable
{ public:
bool collidesWith(Collideable*);
virtual int getMinX() = 0;
virtual int getMaxX() = 0;
virtual int getMinY() = 0;
virtual int getMaxY() = 0;
};
All classes properly override from the virtual methods and the code causing the issue is in bool Collideable::collidesWith(Collideable* c)
According to http://www.cplusplus.com/doc/tutorial/operators/ the logical operators return a boolean value (which makes sense to me, coming from Java) so what's causing this problem?
It is difficult to know if this is what is in the program or a simple transcription problem:
The first line is written ending as c-getMaxX(); maybe it should be c->getMaxX()?
You have c-getMaxX() but you need c->getMaxX(), with a >.

Guidance Needed: Vectors of unique_ptr to dervied classes from an abstract base class

I'm trying to streamline my code and make it work better and easier:
This means diving into vectors and unique_ptr, about which I've read so many good things. However, they are entirely new to me. I have read a few pages on both, but its a lot to wrap my head around.
What I'm currently doing is creating objects of abstract class the traditional way:
VirtualBaseClass* foo1= new DerviedClass1;
VirtualBaseClass* foo2= new DerviedClass2;
VirtualBaseClass* foo3= new DerviedClass3;
But since I have 3 - and quite possibly will have lots more - I want to make it easier to switch between them because I'm going to be comparing any combination of the objects each program run.
Currently, to switch, I just rename the DerviedClass for which I want to instantiate an object so I don't have to go in renaming each foo1 with foo3, etc..
VirtualBaseClass* Generic1 = new DerviedClass3;
VirtualBaseClass* Generic2 = new DerviedClass1;
But ultimately I want the user to tell the program which two objects to compare. So a good starting point seems to make this an array of the VirtualBaseClass, but from research it seems like its pain to have to delete the arrays so people recommend using smart pointers and vectors.
So I tried to use both. For unique pointers I do
unique_ptr<vBaseClass*> foo1(DerviedClass1);
unique_ptr<vBaseClass*> foo2(DerviedClass2);
unique_ptr<vBaseClass*> geneic1 = move(foo1);
However, from what I read I should be doing
unique_ptr<vBaseClass*> foo1(new DerviedClass1);
but new gives error of type specfier but since it works without it I think nothing of it.
With move(foo1) I get an error no move for instance of overload function match and on compile a whole host of other errors such as
unique_ptr<vBaseClass*> champ1 = move(foo1);
error C3867: 'Controller::foo1': function call missing argument list; use '&Controller::foo1' to create a pointer to member
error C2780: '_OutTy *std::move(_InIt,_InIt,_OutTy (&)[_OutSize])' : expects 3 arguments - 1 provided
All this is being done in my Controller.h file btw.
I'm in desperate need of guidances. I don't know if what I'm doing is even neccsary, do I need to use vectors with this? How would I even begin too? Is there a better way of doing this? How do I even get the user to tell the program which object to use? With arrays it would be enter 0 for foo1 or enter 1 for foo2 but with vectors? Is there a better way?
My acutal code
#pragma once
#include "stdafx.h"
#include "Skarner.h"
#include "MasterYi.h"
#include "Riven.h"
using namespace std;
class Controller
{
public:
Controller();
~Controller();
double PCFreq;
__int64 CounterStart;
int CounterCheck;
ofstream out;
Champion* skarner = new Skarner;//old way of doing it
//Champion* yi = new MasterYi;//old way of doing it
//Champion* riven = new Riven;//old way of doing it
//Champion** champions = new Champion*[200];
//Champion[0] = new Skarner();
//unique_ptr<Champion> skarner(Skarner);
unique_ptr<Champion> yi(new MasterYi);// doesn't work new error
unique_ptr<Champion*> riven(Riven); //works with or without *
unique_ptr<Champion*> champ1 = move(riven)//error with move
vector<unique_ptr<Champion>> pChampions;//vector of pointers to champion
//unique_ptr<Champion> champ2;
//Champion *champ1 = dynamic_cast<Champion*>(yi);
//Champion *champ2 = dynamic_cast<Champion*>(skarner);//not sure what the signficance of this is
//Leaving some methods out
};
Wow so apparently you can't use the "new" in a header file only in the cpp file. However I'm still not sure how to make good use of it now that I have it declared in the controller.cpp? I really wanted it as a member variable/instance variable.
Trying to do this. in controller.h
shared_ptr<Champion> yi;
shared_ptr<Champion> riven;
shared_ptr<Champion> skarner;
shared_ptr<Champion> champ1;
shared_ptr<Champion> champ2;
and in the .cpp to define them
Controller::Controller()
{
PCFreq = 0.0;
CounterStart = 0;
out.open("finalStats.txt");
CounterCheck = 0;
yi = shared_ptr<Champion> (new MasterYi);
riven = shared_ptr<Champion>(new Riven);
skarner = shared_ptr<Champion>(new Skarner);
champ1 = move(yi);
champ2 = move(riven);
}
The above code now seems to work but I'm failing to see any direct benefits.
Explanation
You got a * to much:
unique_ptr<vBaseClass> foo1(new DerivedClass1);
should do the trick by allocating a new DerivedClass1 with dynamic storage duration and storing the pointer to it in foo1.
As a reminder, just read the type aloud: foo1has type "unique pointer to vBaseClass".
For the crowd in the comments
The following shows the difference in usage between a raw pointer and a unique pointer:
{
int* a = new int(42);
unique_ptr<int> b(new int(42));
std::cout << *a << ", " << *b << "\n";
delete a;
}
There is no further difference. Any further problem you have is related to a different problem that is hard to pinpoint without further information.
Also, unique_ptr<Champion*> riven(Riven); is a function declaration for a function by the name of riven returning a unique_ptr<Champion*> and taking a single argument of type Riven. The reason this does not error is because it does not do what you think it does at all.
Finally, there is absolutely nothing that makes headers anything special. In fact, C++ performs text substitution before parsing, so that the actual parser does not even know anything about where the code came from anymore!
Karmic Demonstration
Code:
struct champ { virtual std::string whoami() = 0; };
struct karma : champ { std::string whoami() override { return "karma"; } };
int main() {
champ* a = new karma;
std::unique_ptr<champ> b(new karma);
std::cout << a->whoami() << ", " << b->whoami() << "\n";
}
Result:
karma, karma
Proof
unique_ptr<Champion> yi(new MasterYi);// doesn't work new error looks like a function declaration to the compiler, and new isn't valid in that context.
unique_ptr<Champion*> riven(Riven); //works with or without * also looks like a function declaration and is valid with or without the *.
unique_ptr<Champion*> champ1 = move(riven)//error with move You can't move a function into a unique_ptr.
I'm having a really hard time understanding your question but maybe you mean something like this:
unique_ptr<Champion> yi = new MasterYi;
unique_ptr<Champion> riven = new Riven;
std::vector<std::unique_ptr<Champion> > pChampions = { new Skarner };

dereferencing this causes Segmentation fault

I have the following functions
LinearScheme::LinearScheme() {
cout << " empty constructor" << endl;
}
void LinearScheme::init(
int tableId,
std::string &basePath,
std::vector<size_t> &colElemSizes,
TupleDescMap &tupleDescMap,
size_t defaultMaxFragmentSize,
int numCols,
BoundBases &bounds,
std::vector<int> &colsPartitioned )
{
// This linear scheme ignores bounds
// it could be improved to use colsPartitioned for ordering (TODO)
cout << "init Linear Scheme " << endl;
*this = LinearScheme(); //SEGFAULTS HERE
cout << "after cons here?" << endl;
// init private fields
this->tableId_ = tableId;
this->basePath_ = basePath;
this->colElemSizes_ = colElemSizes;
this->numCols_ = numCols;
this->tupleDescMap_ = tupleDescMap;
this->numFragments_ = 0;
this->defaultMaxFragmentSize_ = defaultMaxFragmentSize;
// fragmentSizesFilename_ init
fragmentSizesFilename_ = basePath_ + boost::lexical_cast <string>(tableId_)
+ "_cs";
struct stat st;
// open existing file if exists. Create new otherwise.
if (stat(fragmentSizesFilename_.c_str(), &st) == 0) // file existed
openExisting();
else
createNew();
}
The reason I am initializing in init rather than constructor is because LinearScheme extends a PartitionScheme (super class with virtual methods) class and another class does that where the constructor is used recursively.
I have a QuadTree class which does the same initialization because each QuadTree constructor is applied recursively. *this = QuadTree(bounds, maxSize) line in the init function of QuadTree class works just fine.
however, this line in the other subclass (LinearScheme) *this = LinearScheme() cause a Seg fault.
Any ideas why this might happen?
EDIT
Also replacing the line:
*this = LinearScheme()
with this:
*this;
or removing it overall gets rid of the Seg Fault ... why?
Sounds like incorrect factory method / builder / deferred construction usage. For many of these object creation patterns function that constructs your objects should be a static method because there doesn't yet exist an instance to manipulate. In others you potentially manipulate an already constructed instance. In either case if you are actually constructing the object of the class type within the function you should be using new and eventually returning it.
If you are instead going for a helper method to assist with initialization then you simply shouldn't be constructing the object within the method itself, and you should just be initializing parts of it within your helper.
A factory pattern example:
LinearScheme* LinearScheme::create(...all_your_args....) {
/* construct the thing we are building only if it
* pass any arguments into him that he can handle directly if you'd like
*/
LinearScheme *out = new LinearScheme(...);
/* do whatever else you have to do */
....
return out;
}
or this helper of sorts that you seem to want
/* this time let's just do 'init' on your object */
void LinearScheme::init(....args....) {
/* possibly check if init has been done already */
if ( this->init ) return;
/* proceed to do your initialization stuff
* but don't construct the 'this' instance since it should already exist
*/
this->init = true; //so we don't init again if you don't need multiple init's
}
Alternatively you can consider the delegate constructor methods in C++11 alex mentions.
However neither of these really strikes me as being the actual problem here.
It's not working because either you probably don't even have a valid *this to deference. This could be because of your usage, or it could be because one failed to create potentially because of infinite recursion.
Here's a wikipedia link on the pattern: http://en.wikipedia.org/wiki/Factory_method_pattern
Given what you have said about having to keep passing a dozen arguments around both to parent classes and for your recursive construction, one suggestion you could consider is making a small config struct that you pass along by reference instead of all the discrete parameters. That way you don't have to keep adjusting every signature along the way each time you add / remove another parameter.
The other idea is to seperate entirely the construction of one of your objects from the responsibility of knowing how, where, and when they should be contructed and inserted into your hierarchy. Hard to say without understanding how you will actually be using LinearSchme and what the interface is.
"...in the other subclass (LinearScheme) *this = LinearScheme()"
"The LinearScheme constructor is empty: LinearScheme::LinearScheme()"
if *this is a subclass of LinearMethod, LinearMethod's constructor should already have been called and this line is useless. Besides it calls assignment operator - is it properly defined?
It is better to rely on built-in mechanism of constructing of objects. If you want to avoid code repetition, use C++11 delegating constructors feature. It was specially designed to eliminate "init" methods.
Although, "If there is an infinitely recursive cycle (e.g., constructor C1 delegates to another constructor C2, and C2 also delegates to C1), the behavior is undefined."
So it is up to you to avoid infinite recursion. In your QuadTree you can consider creating nullptr pointers to QuadTreeNode in constructor.