takeaway.o: In function `takeaway':
project:145: undefined reference to `vtable for takeaway'
project:145: undefined reference to `vtable for takeaway'
takeaway.o: In function `~takeaway':
project:151: undefined reference to `vtable for takeaway'
project:151: undefined reference to `vtable for takeaway'
takeaway.o: In function `gameCore':
project.h:109: undefined reference to `gameCore<int>::initialData(int)'
collect2: ld returned 1 exit status
make: *** [takeaway] Error 1
I keep getting this Error from the linker , i know it has something to do with inline functions getting a vtable temporarily stored. But what that entails i am not quite sure. I would assume it has something to do with how i call gameCore's constructor in the initilization list of takeaway.cpp
I have a templated class (gameCore.h)
and a class (takeaway.cpp) that is inheriting from gameCore
The vtable error is called 3 times
1)in takeaways constructor
2) takeaways destructor
3)in gameCores constructor
I am using G++
Here is the code:
(i know it may seem hard to read but i have marked off exatcly where the erros occur)
takeaway.h
#ifndef _TAKEAWAY_H_
#define _TAKEAWAY_H_
#include<map>
#include<cctype>
#include<stack>
#include<map>
#include<iostream>
#include<string>
#include<cstdlib>
#include"gameCore.h"
#include<vector>
using namespace std;
class takeaway : public gameCore<int>
{
private:
public:
// template<class Penny>
void textualGame();
bool isNum(string str);
// template<class Penny>
stack<int> initialData(int initial);
// template<class Position>
int score (int position);
// template<class Position>
stack<int> addStack(int currentPos, stack<int> possiblePositions);
// template<class Penny>
takeaway (int initial);
// template<class Position>
~takeaway();
};
bool isNum(string str);
int charToint(char *theChar);
#endif
takeaway.cpp
/*
Description :
This game communicates with the gameCore class to determine the results
of a game of takeaway played between two computers or a computer and human.
*/
#include "takeaway.h"
/*
Description:Creates a stack represening initial data
Note:Change to a vector eventually
return : stack of int
*/
stack<int> takeaway:: initialData(int initial){
stack<int> returnStack;
int theScore = score(initial);
int final;
if(initial ==0)
{
final = 1;
}
else
{
final = 0;
}
returnStack.push(theScore);
returnStack.push(final);
return returnStack;
}
/*
Description: a textual representation of the game
Note: This is still terribly wrong
*/
void textualGame(){
cout <<"this is the best i could do for a graphical representation";
}
/*
Description: Deetermines if a number is even
Note: Helper function for determining win or loss positions
Returns: 1 if it is and 0 if it is not
*/
int takeaway::score(int position){
if(position % 2 == 0)
{
return 1;
}
return 0;
}
/*
Description: Will return a stack , withouth the given postion in it
will contain all positions possible after the given position
along with anyother that wehre in the given stack.This function
Must also update the map to represent updated positions
Takes: a position to check and a stack to return
Returns: A stack of possible positions.
*/
stack<int> takeaway::addStack(int currentPos, stack<int> possiblePositions ){
if(currentPos != 0)
{
// If even
if( currentPos % 2 == 0)
{
// Create a data aray with score of the new positon and mark it as not final
int data[] = {score(currentPos/2),0};
vector<int> theData(data, data+sizeof(data));
int pos = currentPos/2;
// Add it to the map
//this -> gamesMap[currentPos/2] = dataArray;
this -> gamesMap.insert(std::pair<int, vector<int> >(pos, theData));
// Add it to the possible positions
possiblePositions.push(pos);
}
if(currentPos % 3 == 0)
{
int data[] = {score(currentPos/3),0};
vector<int> theData(data,data+sizeof(data));
int pos = currentPos/3;
//this -> gamesMap[currentPos/3] = dataArray;
this -> gamesMap.insert(std::pair<int, vector<int> >(pos, theData));
possiblePositions.push(pos);
}
// Work for the position that represents taking one penny
int minusFinal = 0;
if(currentPos - 1 == 0)
{
minusFinal = 1;
}
int data[] = {score(currentPos - 1),minusFinal};
vector<int> theData(data,data+sizeof(data));
int pos = currentPos - 1;
// this -> gamesMap[currentPos -1] = dataArary
this->gamesMap.insert(std::pair<int,vector<int> >(pos, theData));
possiblePositions.push(pos);
}
return possiblePositions;
}
/*
Description: Constructor for the takeaway game
OA takes: a initial position, and initial data for it
*/
takeaway::takeaway(int initial):gameCore<int>::gameCore(initial){ //<--- ERROR HERE
//Constructor
}
/*
Description: Destuctor
*/
takeaway::~takeaway(){ // <--------------------- ERROR HERE
//Destructor
}
//checks input and creates game.
int main(int argc, char* argv[]){
int numberPennies ;
string game = argv[0];
if(argc == 2 && isNum(argv[1]) )
{
int pennies = charToint(argv[1]);
takeaway gameInstance(pennies ); // Creates a instance of $
}
// else if(argc == 3 && argv[1] == "play" && isNum(argv[2]) )
// {
// int pennies = charToint(argv[2]);
// takeaway<int> gameInstance(pennies); // Craete a human playab$
// }
else
{
cerr << "Error->Usage: " << game <<" [play] numberOfPennies \n";
exit (1);
}
return 0;
}
//Converts a char to a integer
int charToint(char *theChar){
int theInt = atoi(theChar);
return theInt;
}
//Determines if a string is numeric
bool isNum(string str){
for(int i = 0;i < str.length() ;i++){
if(isdigit(str[i]) != 1)
{
cerr << "Error->Input: Number must be a Positive Integer the charecter '" << str[i]<< "' invalidated your input. \n" ;
exit(1);
return false;
}
}
return true;
}
gameCore.h
/*
gameCore.h
Description:
This class created gameMap that are written as a template
They will communicate with the specific game and the algorithm
To keep track of positions ans there values.
*/
#ifndef GAMECORE_H
#define GAMECORE_H
#include <map>
#include <stack>
#include <string>
#include <vector>
using namespace std;
template <class Position>
class gameCore
{
protected:
//Best Move used by algorithim
Position bestMove;
//The current highest score used by the algorithim
int highestScore ;
//Stack to be used to remmeber what move created the score
stack<Position> movedFrom;
//Stack used for the algorithim.
stack<Position> curWorkingPos;
//The actual Map that the data will be held in.
map<Position,vector<int> > gamesMap;
public:
/*
Description : finds the data array for a poisition
takes: a Position
Returns: a array of integers /**
*/
virtual stack<int> initialData(Position pos) = 0;
/*
Description: Game must implement a way to determine a positions
score.
*/
virtual int score(Position pos) = 0;
/*
Description: A Graphical representation of the game
*/
virtual void textualGame() = 0;
/*
Description: a virtual function implemented by the child class
it will return a stack without the given position in it.This stack
will contain all positions available from the given postion as well as
all position already in the given stack. Also it will update the map with
all generated positions.
TAkes: a postion to check and a stack of currently working positons.
*/
virtual stack<Position> addStack(Position currentPos, stack<Position> possiblePositions ) = 0;
/*
Description:Constructor that
Creates a Map with positions as the key.
And an array of two integers that represent the positions
value and if we have moved here in the past.
Takes: a Initial Position and a Array of integers
*/
gameCore(Position initial){ // <-----ERROR HERE
//Determine the initial data and add it to the map and queue.
stack<int> theData = initialData(initial);
int first = theData.top();
theData.pop();
int second = theData.top();
theData.pop();
int initialData[] = {first,second};
vector<int> posData(initialData,initialData+sizeof(initialData));
gamesMap[initial] = posData;
curWorkingPos.push(initial);
}
/*
Description:
A destructor for the class
*/
~gameCore(){
//I do nothing but , this class needs a destructor
}
/*
Description: Takes the current position and returns
that positions Score.
Takes: A position
Returns:A integer that is a positions score.
*/
int getPosScore(Position thePos) const {
return this ->gamesMap.find(thePos)->second[0];
}
/*
Description: Adds values to a stack based on the current position
Takes: a poistion
*/
void updateStack(Position curPos){
this ->curWorkingPos =addStack(curPos,this ->curWorkingPos ); // get a stack from the game
// The game has a function that takes a position and a stack and based on the positions returns a stack identical to the last but with added values that represent valid moves from the postion./
}
/*
Description : Takes a positions and returns a integer
that depends on if the position is a final pos or not
Takes: A position
Returns: A Bool that represents if the position is a final(1) or not (0).
*/
// Possible change
bool isFinal(Position thePos) {
typename map<Position,vector<int> >::iterator iter = this ->gamesMap.find(thePos);
return iter->second[1] == 1 ;
}
/*
Description: Based on the given position determine if a move needs to be made.
(if not this is a end game position and it will return itself) If a move needs
to be made it will return the position to move to that is ideal.
Note: (because all positions can be represented as integers for any game , the return
type is a integer)
*/
int evaluatePosition(Position possiblePosition ){
if(isFinal(possiblePosition)) //If this is a final position
{
return getPosScore(possiblePosition); //Return the score
}
else
{
updateStack(possiblePosition); //Put all possible positions from this in thte stack
while(this -> curWorkingPos.size() != 0)
{
this -> movedFrom.push(this->curWorkingPos.front()); //take the top of the possible positions stack and set it the the moved from stack
this -> curWorkingPos.pop();
int curScore = evaluatePosition(this ->movedFrom.top()); //Recursive call for school
curScore = curScore * -1; //Negate the score
if(curScore > this -> highestScore) // if the score resulting from this position is biggest seen
{
highestScore = curScore;
this ->movedFrom.pop(); //do this first to get rid of the the lowest point
this -> bestMove = this ->movedFrom.top(); // mark where the lowest point came from
}
else
{
this -> movedFrom.pop();
}
}
}
return this -> bestMove;
}
//A Structure to determine if a position has a lower value than the second
struct posCompare{
bool operator() (Position pos1,Position pos2) const {
return (pos1.getPosScore() < pos2.getPosScore());
}
};
};
#endif
One or more of your .cpp files is not being linked in, or some non-inline functions in some class are not defined. In particular, takeaway::textualGame()'s implementation can't be found. Note that you've defined a textualGame() at toplevel, but this is distinct from a takeaway::textualGame() implementation - probably you just forgot the takeaway:: there.
What the error means is that the linker can't find the "vtable" for a class - every class with virtual functions has a "vtable" data structure associated with it. In GCC, this vtable is generated in the same .cpp file as the first listed non-inline member of the class; if there's no non-inline members, it will be generated wherever you instantiate the class, I believe. So you're probably failing to link the .cpp file with that first-listed non-inline member, or never defining that member in the first place.
The first set of errors, for the missing vtable, are caused because you do not implement takeaway::textualGame(); instead you implement a non-member function, textualGame(). I think that adding the missing takeaway:: will fix that.
The cause of the last error is that you're calling a virtual function, initialData(), from the constructor of gameCore. At this stage, virtual functions are dispatched according to the type currently being constructed (gameCore), not the most derived class (takeaway). This particular function is pure virtual, and so calling it here gives undefined behaviour.
Two possible solutions:
Move the initialisation code for gameCore out of the constructor and into a separate initialisation function, which must be called after the object is fully constructed; or
Separate gameCore into two classes: an abstract interface to be implemented by takeaway, and a concrete class containing the state. Construct takeaway first, and then pass it (via a reference to the interface class) to the constructor of the concrete class.
I would recommend the second, as it is a move towards smaller classes and looser coupling, and it will be harder to use the classes incorrectly. The first is more error-prone, as there is no way be sure that the initialisation function is called correctly.
One final point: the destructor of a base class should usually either be virtual (to allow polymorphic deletion) or protected (to prevent invalid polymorphic deletion).
If a class defines virtual methods outside that class, then g++ generates the vtable only in the object file that contains the outside-of-class definition of the virtual method that was declared first:
//test.h
struct str
{
virtual void f();
virtual void g();
};
//test1.cpp
#include "test.h"
void str::f(){}
//test2.cpp
#include "test.h"
void str::g(){}
The vtable will be in test1.o, but not in test2.o
This is an optimisation g++ implements to avoid having to compile in-class-defined virtual methods that would get pulled in by the vtable.
The link error you describe suggests that the definition of a virtual method (str::f in the example above) is missing in your project.
You may take a look at this answer to an identical question (as I understand):
https://stackoverflow.com/a/1478553
The link posted there explains the problem.
For quick solving your problem you should try to code something like this:
ImplementingClass::virtualFunctionToImplement(){...}
It helped me a lot.
Missing implementation of a function in class
The reason I faced this issue was because I had deleted the function's implementation from the cpp file, but forgotten to delete the declaration from the .h file.
My answer doesn't specifically answer your question, but lets people who come to this thread looking for answer know that this can also one cause.
it suggests that you fail to link the explicitly instantiated basetype public gameCore (whereas the header file forward declares it).
Since we know nothing about your build config/library dependencies, we can't really tell which link flags/source files are missing, but I hope the hint alone helps you fix ti.
GNU linker, in my case companion of GCC 8.1.0, well detects not re-declared pure virtual methods, but above certain complexity of class design it fails to identify missing implementation of methods and answers with a flat "V-Table Missing",
or even tends to report missing implementation, in spite it is there.
The only solution then is to verify consistency of declaration of implementation manually, method by method.
if you have virutal deconstruct function, you need to write it like this: ~SubListener() override = default; , don't forget this =default
Related
I'm creating a program that will simulate a race between various runners, using behavior classes to implement different types of runner movements.
To do this, an abstract MoveBehaviour class will be implemented, along with several other concrete sub-classes (etc. WalkBehaviour, SleepBehaviour, SlideBehaviour).
The abstract MoveBehaviour class will require a pure virtual move() function, and the appropriate behaviour will be implemented in the concrete sub-classes. This move() function computes a new position newPos for the runner, given its current position oldPos, and the move() function will return a short, text description of the move in the log parameter (Etc. "walk forward 1 step") , which will be printed to the screen in a later step. I feel as if I'm not returning my log values in these functions correctly, and this relates to another issue.
In the update() function in Runner.cc, I'm supposed to randomly select the runner’s next move behaviour. This involves a new walking behaviour 40% of the time, a sleeping behaviour 40% of the time, and a slide behaviour 20% of the time. I'm supposed to use the new behaviour object to compute a new position that will be stored in the newPos parameter, and then I am to document the move in the runner’s current log data member. Etc if the runner is named Timmy, and the new move behaviour is walking, the current log data member will store the string “Timmy walked one step.”
Going back to my log, I wasn't sure how I would access the string that I declared in each of the move functions for every behaviour class. I noticed there is a getLog() function in Runner.cc, but I feel like it doesn't make sense to use that. This makes me thing I wasn't supposed to declare the "walked one step" strings and such in the move classes but rather in the update classes instead.
Additionally, I don't understand how to get the new behaviour object to compute a new position that will be stored in the newPos parameter and would appreciate some help with that as well.
For getting the log values, I'm just printing the runner's name below and my attempt was going to append whatever was in the log value to this sentence, but I wasn't sure how to access the log values.
I can include the SleepBehaviour and SlideBehaviour classes if needed, but they are practically identical to WalkBehaviour and I figured only one example was needed.
Runner.cc
void Runner::update(Position& newPos){
int r;
r = random(100) + 1;
if(r <= 40){
WalkBehaviour* walk = new WalkBehaviour;
}else if (r <= 40){
SleepBehaviour sleep = new SleepBehaviour;
}else{
SlideBehaviour* slide = new SlideBehaviour;
}
cout << name << endl;
}
Position.cc
#include <iostream>
using namespace std;
#include <string>
#include "Position.h"
Position::Position(int i1, int i2) : row(i1), column(i2){
}
Position::getRow(){ return row; }
Position::getColumn(){ return column; }
void Position::setRow(int r){ row = r; }
void Position::setColumn(int c){ column = c; }
MoveBehaviour.h
#ifndef MOVEBEHAVIOUR_H
#define MOVEBEHAVIOUR_H
#include <iostream>
#include "Position.h"
using namespace std;
class MoveBehaviour
{
public:
virtual void move(Position&, Position&, string&) = 0;
virtual ~MoveBehaviour() = default;
};
class WalkBehaviour : public MoveBehaviour{
public:
virtual void move(Position&, Position&, string&);
virtual ~WalkBehaviour();
};
class SleepBehaviour : public MoveBehaviour{
public:
virtual void move(Position&, Position&, string&);
virtual ~SleepBehaviour();
};
class SlideBehaviour : public MoveBehaviour{
public:
virtual void move(Position&, Position&, string&);
virtual ~SlideBehaviour();
};
WalkBehaviour.cc
#include <iostream>
using namespace std;
#include <string>
#include "MoveBehaviour.h"
void WalkBehaviour::move(Position& oldPos, Position& newPos, string& log) {
newPos.setColumn(oldPos.getColumn() + 1);
newPos.setRow(oldPos.getRow());
log = (" walked one step \n");
}
WalkBehaviour::~WalkBehaviour(){}
First, you need to actually use polymorphism by declaring a pointer to a base MoveBehaviour object that you let point to a derived instance.
Additionally, you need to make sure that you don't leak memory, so I chose std::unique_ptr which is automatically freed upon function exit.
Next, you can simply pass an empty std::string for the function to assign the log to, and use a std::stringstream to construct a line with the name with the move description. The output of this stringstream is then added to the log member in one go.
void Runner::update(Position& newPos) {
int r;
r = random(100) + 1;
std::unique_ptr<MoveBehaviour> movement;
if(r <= 40) {
movement = make_unique<WalkBehaviour>();
} else if (r <= 80) {
movement = make_unique<SleepBehaviour>();
} else {
movement = make_unique<SlideBehaviour>();
}
std::string moveLog;
movement->move(currPos, newPos, moveLog);
currPos = newPos;
std::stringstream ss;
ss << name << " " << moveLog << std::endl;
log += ss.str();
}
Here:
if(r <= 40){
WalkBehaviour* walk = new WalkBehaviour;
}else if (r <= 40){
SleepBehaviour sleep = new SleepBehaviour;
}else{
SlideBehaviour* slide = new SlideBehaviour;
}
you are creating new behaviors and immediately leaking them. You should have assign them ti Runner's MoveBehaviour* behaviour;, deleting its old behavior first:
delete behaviour;
if(r <= 40){
behaviour = new WalkBehaviour;
}else if (r <= 40){
behaviour = new SleepBehaviour;
}else{
behaviour = new SlideBehaviour;
}
Your WalkBehaviour::move() uses log correctly (except that you don't need to enclose text literal into ()
Well, I just started learning c++ and i seem to have some problem. To be specific i have to make a program that recreates the game musical chairs. For this i was supposed to make two classes one named member that would have the position of a player and their id number and also point to the next (last member should point to first.). Second a class named chain that would point at the first member and also have the total number of exsting players. For starters i should create the chain based on a parametre N that would give every member a random id and position them and of course link the powers with each other.
What i wrote was
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Member{
public:
int position, number;
Member *next_member;
void Member2( Member *member_, int pos, int id,int N){
if(pos <= N){
member_->position=pos;
member_->number=id;
Member2 (member_->next_member, pos++, rand(), N);
if(pos == N)
member_->next_member = this;
}
}
};
class Chain {
Member *First_member;
int size;
public:
Chain ( int N){
size = N;
srand(time(NULL));
First_member->Member2(First_member, 1 , rand(), N);
}
};
and the main just called chain.
The problem is that when Member2 is called by itself, the whole thing crashes. Any help is good.
Edit: When trying to debug it, it seems there is segmentantion fault when membber_ is used after Member2 has called the Member2 isnide it.
The expression pos++ uses post increment, which produces the original value of pos as the expression result. Thus the pos argument does not increase in the recursive call. Thus, you get infinite recursion, which if you're lucky crashes when it's used up all stack space.
There are several issues (at least) with that code:
1)
Member *First_member;
is only a declaration. To turn it into a definition, you need to actually allocate memory, e.g:
Member *First_member = new Member;
and also release it in the end, e.g. (not necessarily the best way to do it, but my C++ is a little rusty):
void free(Member* _member) {
Member* _next = _member->next_member;
if (_next!=NULL) free(_next);
delete _member;
}
Member* First_member = new Member;
// some code ...
free(First_member);
2) More serious problem is your Member2 method: it does not check whether its Member *member_ arguments is not NULL (in which case the code will indeed crash, because it tries to work with garbage as if it was data).
3) Member2 should also take care about allocating memory for the next element in the chain, e.g.:
if (member_->next_member == NULL) {
member->next_member = new Member;
}
Member2 (member_->next_member, pos++, rand(), N);
I'm trying to implement a minheap in C++. However the following code keeps eliciting errors such as :
heap.cpp:24:4: error: cannot convert 'complex int' to 'int' in assignment
l=2i;
^
heap.cpp:25:4: error: cannot convert 'complex int' to 'int' in assignment
r=2i+1;
^
heap.cpp: In member function 'int Heap::main()':
heap.cpp:47:16: error: no matching function for call to 'Heap::heapify(int [11], int&)'
heapify(a,i);
^
heap.cpp:47:16: note: candidate is:
heap.cpp:21:5: note: int Heap::heapify(int)
int heapify(int i) //i is the parent index, a[] is the heap array
^
heap.cpp:21:5: note: candidate expects 1 argument, 2 provided
make: * [heap] Error 1
#include <iostream>
using namespace std;
#define HEAPSIZE 10
class Heap
{
int a[HEAPSIZE+1];
Heap()
{
for (j=1;j<(HEAPISZE+1);j++)
{
cin>>a[j];
cout<<"\n";
}
}
int heapify(int i) //i is the parent index, a[] is the heap array
{
int l,r,smallest,temp;
l=2i;
r=2i+1;
if (l<11 && a[l]<a[i])
smallest=l;
else
smallest=i;
if (r<11 && a[r]<a[smallest])
smallest=r;
if (smallest != i)
{
temp = a[smallest];
a[smallest] = a[i];
a[i]=temp;
heapify(smallest);
}
}
int main()
{
int i;
for (i=1;i<=HEAPSIZE;i++)
{
heapify(a,i);
}
}
}
Ultimately, the problem with this code is that it was written by someone who skipped chapters 1, 2 and 3 of "C++ for Beginners". Lets start with some basics.
#include <iostream>
using namespace std;
#define HEAPSIZE 10
Here, we have included the C++ header for I/O (input output). A fine start. Then, we have issued a directive that says "Put everything that is in namespace std into the global namespace". This saves you some typing, but means that all of the thousands of things that were carefully compartmentalized into std:: can now conflict with names you want to use in your code. This is A Bad Thing(TM). Try to avoid doing it.
Then we went ahead and used a C-ism, a #define. There are times when you'll still need to do this in C++, but it's better to avoid it. We'll come back to this.
The next problem, at least in the code you posted, is a misunderstanding of the C++ class.
The 'C' language that C++ is based on has the concept of a struct for describing a collection of data items.
struct
{
int id;
char name[64];
double wage;
};
It's important to notice the syntax - the trailing ';'. This is because you can describe a struct and declare variables of it's type at the same time.
struct { int id; char name[64]; } earner, manager, ceo;
This declares a struct, which has no type name, and variables earner, manager and ceo of that type. The semicolon tells the compiler when we're done with this statement. Learning when you need a semicolon after a '}' takes a little while; usually you don't, but in struct/class definition you do.
C++ added lots of things to C, but one common misunderstanding is that struct and class are somehow radically different.
C++ originally extended the struct concept by allowing you to describe functions in the context of the struct and by allowing you to describe members/functions as private, protected or public, and allowing inheritance.
When you declare a struct, it defaults to public. A class is nothing more than a struct which starts out `private.
struct
{
int id;
char name[64];
double wage;
};
class
{
public:
int id;
char name[64];
double wage;
};
The resulting definitions are both identical.
Your code does not have an access specifier, so everything in your Heap class is private. The first and most problematic issue this causes is: Nobody can call ANY of your functions, because they are private, they can only be called from other class members. That includes the constructor.
class Foo { Foo () {} };
int main()
{
Foo f;
return 0;
}
The above code will fail to compile, because main is not a member of Foo and thus cannot call anything private.
This brings us to another problem. In your code, as posted, main is a member of Foo. The entry point of a C++ program is main, not Foo::main or std::main or Foo::bar::herp::main. Just, good old int main(int argc, const char* argv[]) or int main().
In C, with structs, because C doesn't have member functions, you would never be in a case where you were using struct-members directly without prefixing that with a pointer or member reference, e.g. foo.id or ptr->wage. In C++, in a member function, member variables can be referenced just like local function variables or parameters. This can lead to some confusion:
class Foo
{
int a, b;
public:
void Set(int a, int b)
{
a = a; // Erh,
b = b; // wat???
}
};
There are many ways to work around this, but one of the most common is to prefix member variables with m_.
Your code runs afoul of this, apparently the original in C passed the array to heapify, and the array was in a local variable a. When you made a into a member, leaving the variable name exactly the same allowed you not to miss the fact that you no-longer need to pass it to the object (and indeed, your heapify member function no-longer takes an array as a pointer, leading to one of your compile errors).
The next problem we encounter, not directly part of your problem yet, is your function Heap(). Firstly, it is private - you used class and haven't said public yet. But secondly, you have missed the significance of this function.
In C++ every struct/class has an implied function of the same name as the definition. For class Heap that would be Heap(). This is the 'default constructor'. This is the function that will be executed any time someone creates an instance of Heap without any parameters.
That means it's going to be invoked when the compiler creates a short-term temporary Heap, or when you create a vector of Heap()s and allocate a new temporary.
These functions have one purpose: To prepare the storage the object occupies for usage. You should try and avoid as much other work as possible until later. Using std::cin to populate members in a constructor is one of the most awful things you can do.
We now have a basis to begin to write the outer-shell of the code in a fashion that will work.
The last change is the replacement of "HEAPSIZE" with a class enum. This is part of encapsulation. You could leave HEAPSIZE as a #define but you should expose it within your class so that external code doesn't have to rely on it but can instead say things like Heap::Size or heapInstance.size() etc.
#include <iostream>
#include <cstdint> // for size_t etc
#include <array> // C++11 encapsulation for arrays.
struct Heap // Because we want to start 'public' not 'private'.
{
enum { Size = 10 };
private:
std::array<int, Size> m_array; // meaningful names ftw.
public:
Heap() // default constructor, do as little as possible.
: m_array() // says 'call m_array()s default ctor'
{}
// Function to load values from an istream into this heap.
void read(std::istream& in)
{
for (size_t i = 0; i < Size; ++i)
{
in >> m_array[i];
}
return in;
}
void write(std::ostream& out)
{
for (size_t i = 0; i < Size; ++i)
{
if (i > 0)
out << ','; // separator
out << m_array[i];
}
}
int heapify(size_t index)
{
// implement your code here.
}
}; // <-- important.
int main(int argc, const char* argv[])
{
Heap myHeap; // << constructed but not populated.
myHeap.load(std::cin); // read from cin
for (size_t i = 1; i < myHeap.Size; ++i)
{
myHeap.heapify(i);
}
myHead.write(std::cout);
return 0;
}
Lastly, we run into a simple, fundamental problem with your code. C++ does not have implicit multiplication. 2i is the number 2 with a suffix. It is not the same as 2 * i.
int l = 2 * i;
There is also a peculiarity with your code that suggests you are mixing between 0-based and 1-based implementation. Pick one and stick with it.
--- EDIT ---
Technically, this:
myHeap.load(std::cin); // read from cin
for (size_t i = 1; i < myHeap.Size; ++i)
{
myHeap.heapify(i);
}
is poor encapsulation. I wrote it this way to draw on the original code layout, but I want to point out that one reason for separating construction and initialization is that it allows initialization to be assured that everything is ready to go.
So, it would be more correct to move the heapify calls into the load function. After all, what better time to heapify than as we add new values, keeping the list in order the entire time.
for (size_t i = 0; i < Size; ++i)
{
in >> m_array[i];
heapify(i);
}
Now you've simplified your classes api, and users don't have to be aware of the internal machinery.
Heap myHeap;
myHeap.load(std::cin);
myHeap.write(std::cout);
I wrote my code like this inside a class to calculate max distance from source to node. Now I need to take it out of the class and have a similar function to calculate my distances but by using Djikstra. So, I would need to pass this city vector and source being one of my vertex ( this will loop over vertices ) and return a distance from this function back to class for my next computation. I am running out of time so help me.
int distanceToNearCity(int cityIdOfStore, const std::vector<City> & AllCities) const
{
// is there a store in this city ?
if (storeExists || cityId == cityIdOfProposedNewStore)
{
return 0; // 0 distance
}
int distance = TOOFAR; // initialise with more than max allowed
for (int i=0; i<connectingCities.size(); ++i)
{
int id = connectingCities[i];
if (AllCities[id-1].hasStore() || AllCities[id-1].getId() == cityIdOfProposedNewStore)
{
// we have a store (or proposed one) here, but is it's distance more than other stores ?
if (distances[i] < distance)
{
distance = distances[i];
}
}
}
return distance;
}
How can I pass these class objects to function which is public.Thanks!!
Well, accessing internal member variables from main is problably a bad design, breaks encapsulation, is a possible source of problems, thus not a good idea.
Solution 1
Let's say your class is called MyOriginal. Make distanceToNearCity virtual. Create a derived class MyDerived and rewrite distanceToNearCity so that implements Djikstra. In the derived class you can access the original member variables from MyOriginal, as long as they are public or protected. The user (main) does not need to know the implementation details.
Solution 2
Rewrite the original distanceToNearCity method so, that it has no side effects as it ware a static method. This means that it does not need access to any of the member variables. Pass all arguments to the method via parameters. I mentioned 'as it was a static method', since the method will not be the member of the original MyOriginal class. Make MyOriginal a template class, implement distanceToNearCity in an external class and pass this class as a template argument to MyOriginal. As a non member, you can implement any number of distance algorithms and pass them to the original class. This solution has the advantage, that the call to the 'virtual' method is known at the compile time, so it produces faster code.
template<class T> // T will contain distance computation
class MyOriginal
{
public:
void process()
{
.. // your staff
int distance = T::distanceToNearCity(necessary arguments); // call the external implementation
.. // rest of your staff
}
};
class OriginalDistance
{
public:
static int distanceToNearCity(necessary arguments); // your original implementation
};
class DjikstraDistance
{
public:
static int distanceToNearCity(necessary arguments); // another distance computation
};
int main(int argc, char *argv[])
{
MyOriginal<DjikstraDistance> myInstance;
myInstance.process(); // call processing, use DjikstraDistance::distanceToNearCity() inside
}
Solution 3
If you from some reason dislike both previous implementations, you can use a 'c' style solution. Create a type which represents a signature of the distanceToNearCity method.
Write 'distanceToNearCityOriginal' and 'distanceToNearCityDjikstra' functions. Pass a pointer to desired function as a paramter the MyOriginal::process method. C++ developers will dislike you.
typedef int (DistanceAlgo*)(necessary arguments); // pointer to a function which returns int
int distanceToNearCityOriginal(necessary arguments); // first implementation of distance
int distanceToNearCityDjikstra(necessary arguments); // second implementation of distance
class MyOriginal
{
public:
void process(DistanceAlgo algo)
{
.. // your staff
int distance = (*algo)(necessary arguments); // call the external implementation
.. // rest of your staff
}
};
int main(int argc, char *argv[])
{
DistanceAlgo algo = &distanceToNearCityDjikstra; // choose djikstra
MyOriginal myInstance;
myInstance.process(algo); // call processing, use distanceToNearCityDjikstra inside
}
I have a pretty standard class with some public member functions and private variables.
My problem originally stems from not being able to dynamically name object instances of my class so I created an array of pointers of the class type:
static CShape* shapeDB[dbSize];
I have some prompts to get info for the fields to be passed to the constructor (this seems to work):
shapeDB[CShape::openSlot] = new CShape(iParam1,sParam1,sParam2);
openSlot increments properly so if I were to create another CShape object, it would have the next pointer pointing to it. This next bit of code doesn't work and crashes consistently:
cout << shapeDB[2]->getName() << " has a surface area of: " << shapeDB[2]->getSA() << shapeDB[2]->getUnits() << endl;
The array of pointers is declared globally outside of main and the get() functions are public within the class returning strings or integers. I'm not sure what I'm doing wrong but something relating to the pointer set up I'm sure. I'm writing this code to try and learn more about classes/pointers and have gotten seriously stumped as I can't find anyone else trying to do this.
I'm also curious as to what the CShape new instances get named..? if there is any other way to dynamically create object instances and track the names so as to be able to access them for member functions, I'm all ears.
I've tried all sorts of permutations of pointer referencing/de-referencing but most are unable to compile. I can post larger chunks or all of the code if anyone thinks that will help.
class CShape {
int dim[maxFaces];
int faces;
string units;
string type;
string name;
bool initialized;
int slot;
public:
static int openSlot;
CShape();
CShape(int, string, string); // faces, units, name
~CShape();
void initialize(void);
// external assist functions
int getA(void) {
return 0;
}
int getSA(void) {
int tempSA = 0;
// initialize if not
if(initialized == false) {
initialize();
}
// if initialized, calculate SA
if(initialized == true) {
for(int i = 0; i < faces; i++)
{
tempSA += dim[i];
}
return(tempSA);
}
return 0;
}
string getUnits(void) {
return(units);
}
string getName(void) {
return(name);
}
// friend functions
friend int printDetails(string);
};
// constructor with values
CShape::CShape(int f, string u, string n) {
initialized = false;
faces = f;
units = u;
name = n;
slot = openSlot;
openSlot++;
}
My guess is you use the CShape constructor to increment CShape::openSlot?
You're probably changing the value before it's read, thus the pointer is stored in a different location.
Try replacing openSlot with a fixed value to rule out this CShape::option.
-- code was added --
I'm pretty sure this is the problem, the constructor is executed before the asignment, which means the lhs. will be evaluated after CShape::openSlot is incremented.