Accessing member parent function to child - c++

The problem is I have a Sort parent class (Sorter) and many children( merge,bubble,quick)
What I m trying to do is to access the function "runOnce" which is a function in parent class.
Main.cpp
int main()
{
fstream Data;
Data.open("Test.txt",ios::in|ios::out);
Sorter<int>* bubble = new BubbleSort<int>;
Sorter<int>* quick = new QuickSort<int> ;
Sorter<int>* merge = new MergeSort<int> ;
vector<int> list;
while(!Data.eof())
{
int temp;
Data >> temp;
list.push_back(temp);
}
Sorter<int>::runOnce(bubble, list);
Data.close();
}
Sorter.cpp
#ifndef SORTER_H
#define SORTER_H
#include <vector>
using namespace std;
template <class T>
class Sorter {
public:
Sorter(){};
virtual void sort(vector<T>&, int, int) = 0;
double runOnce(Sorter<T>&, vector<T>&);
};
#endif // SORTER_H
but I m getting an error in main in line of
Sorter::runOnce(bubble, list);
it says:
no matching function for call to 'sorter::
runOnce(Sorter*&, std:: vector < int , std :: allocator < int > > &)
And I tried to change it to be
bubble->Sorter->runOnce(bubble, list);
and it said
invalid use of Sorter< int >::Sorter
How can I fix this?

The function takes a Sorter&, not a Sorter*&. Dereference the pointer when passing it in, e.g:
Sorter<int>::runOnce(*bubble, list);

I Solved it with making runOnce a function in the main and calling it and it solved everything. Also I used the header files of the parent class in the children because I was using the cpp file.

Related

Not all of my constructors are being imported?

I'm making a heap class to be importable with heap.h and my constructors including bool types do not work, yet every other constructor and function imported works.
Here is what's in heap.h:
#ifndef __HEAP_INCLUDED__
#define __HEAP_INCLUDED__
#include <iostream>
#include <vector>
using namespace std;
class heap{
int capacity;
bool isMinHeap; //1 is min heap -- ascending order
vector<int> * content;
public:
heap();
heap(bool t);
heap(vector<int> * input);
heap(vector<int> * input, bool t);
void print();
void prettyPrint();
int parent(int i);
int leftChild(int i);
int rightChild(int i);
int size();
int getMax();
void insert(int data);
void heapifyDown(int index);
void heapifyUp(int index);
int invalidChild(int index);
int deleteMax();
int deleteMin();
bool minDir();
int at(int index);
};
vector<int> * heapSort(vector<int> * input);
void swap(vector<int> * vec, int a, int b);
#endif
Here are the defined constructors in heap.cpp. Note, all constructors work fine when I add a main to this file to test stuff:
class heap{
vector<int> * content;
int capacity = 256;
bool isMinHeap; //1 is min heap -- ascending order
public:
heap(){
content = new vector<int>;
isMinHeap = 0;
}
heap(bool t){
content = new vector<int>;
isMinHeap = t;
}
heap(vector<int> * input){
content = input;
isMinHeap = true;
for(int i = content->size()/2; i >= 0; i--){
heapifyDown(i);
}
}
heap(vector<int> * input, bool t){
content = input;
isMinHeap = t;
for(int i = content->size()/2; i >= 0; i--){
heapifyDown(i);
}
}
//other functions below
}
The constructors with bool do not work in main.cpp, which has #include "heap.h" at the top. The files are all in the same directory and I am compiling with this command: g++ heap.cpp main.cpp -o main. Why do two of my constructors not work?
The error I see is
/usr/bin/ld: /tmp/ccwomODk.o: in function `main':
main.cpp:(.text+0x4e2): undefined reference to `heap::heap(bool)'
collect2: error: ld returned 1 exit status
-Wall does not elaborate on the issue. I'm pretty sure the issue is with my linking somewhere because the constructors work inside of heap.cpp when I use them in there.
What you are doing with the class in the .cpp file is wrong. You are not allowed to define the class twice. There must only be one class heap { /*...*/ }; in the program (but it may be included in multiple .cpp files). Otherwise the one-definition-rule (ODR) is violated and the program has undefined behavior.
So remove everything you are showing from heap.cpp.
To define the constructors of heap in the heap.cpp file, you need to use this syntax:
#include "heap.h"
heap::heap() {
/*...*/
}
heap::heap(bool t) {
/*...*/
}
//...
and so on. The other member functions must be defined in a similar way, e.g.:
void heap::print() {
/*...*/
}
Furthermore, if you want to have a default member initializer as in
int capacity = 256;
add it in the declaration in the .h file instead.
I also want to add that having a pointer-to-std::vector as member is almost surely a wrong approach as well, but out-of-scope for the question.
When you declare a program element such as a class, function, or
variable, its name can only be "seen" and used in certain parts of
your program. The context in which a name is visible is called its
scope. For example, if you declare a variable x within a function, x
is only visible within that function body.
It seems you broke ODR rule so bad. Your class members including constructors has no body declared in the source file(heap.cpp).
Use '::' to make class members have a body:
//heap.cpp
"heap.h"
heap::heap()
{
}
heap:heap(vector<int> * input, bool t)
{
}
int heap::parent(int i)
{
return i;
}
// this is how you create a body for function that are class members
// the same should be done for all other functions

invalid pointer when using strings for generic class

So this is for my data structures class and I am struggling to understand why I am getting the error: invalid pointer: 0x00000000023ce048 ***. It only happens when I define my generic class using strings: NSequence<string> v3(10);
It should be noted that using int or even a different class worked fine. However, as soon as I write the line: NSequence<string> v3(10); I get the pointer error and I have no idea why?
UPDATE:
I've found that it was actually my destructor class that was causing the error. However, I now have no idea why this would cause an error specifically with string?
template<typename T>
NSequence<T>::~NSequence()
{
delete items;
}
Here is the definition of my class:
#include <algorithm>
#include <iostream>
#include <utility>
/* XXX: Implement all member functions for NSequence in NSequence.hpp */
template <typename T>
class NSequence
{
public:
explicit NSequence( int initSize = 0 );
private:
int numOfItems;
int totalCapacity;
T * items;
};
#include "NSequence.hpp" // do not change this line
#endif
Here is my constructor function:
template<typename T>
NSequence<T>::NSequence(int initSize)
{
if(initSize==0)
initSize=1;
numOfItems = initSize;
totalCapacity = initSize;
items = new T[totalCapacity];
}
Any advice would be greatly appreciated!

Program stops - move array to function | C++

I have 2 classes.
First Class - Midgam - The constructor has the following line:
midgam = new Vector[20];
The second class - Vector - where I create an array named array.
The program works great just that I have a little problem.
At the end of the program I try to print in alphabetical order, I use the BubbleSort sorting. The sorting works fine but something in the Swap function stops.
This is how it looks:
void Midgam::Swap(Vector *xp, Vector *yp) {
Vector temp = *xp;
cout << temp.getName() << endl;
*xp = *yp;
*yp = temp;
}
void Midgam::bubbleSort() {
int i, j;
for (i = 0; i < iterator - 1; i++) {
for (j = 0; j < iterator - i - 1; j++) {
if (midgam[j].getName().compare(midgam[j+1].getName()) > 0) {
Swap(&midgam[j], &midgam[j+1]);
}
}
}
}
I work with Visual Studio, the program stops and the program shows me the following code snippet in the Vector class:
Vector::~Vector() {
if (array)
delete[] array;
}
full definitions of Midgam:
#include <iostream>
#include <string>
#include "Vector.h"
using namespace std;
#ifndef MIDGAM_H_
#define MIDGAM_H_
class Midgam {
private:
int boxNum;
int maxParties;
int iterator;
Vector *midgam;
public:
Midgam(int num_of_boxes, int num_of_parties);
virtual ~Midgam();
void Start();
void Menurmal();
void SumOfEzor();
double SumOfParty(string name);
int SumAllVotes();
void AddParty();
void Swap(Vector *xp, Vector *yp);
void bubbleSort();
void Histograma();
void PrintStars(int num);
int FindPartyByName(string party);
void PrintAll();
};
#endif /* MIDGAM_H_ */
full definitions of Vector:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#ifndef VECTOR_H_
#define VECTOR_H_
class Vector {
private:
string name;
int size;
unsigned int *array;
bool Bool;
public:
Vector(string name, int size);
Vector();
Vector & operator=(const Vector &);
virtual ~Vector();
bool StringToArray(string str);
bool getBool();
string getName();
unsigned int getAddress();
int getSize();
unsigned int getValueFromArray(int index);
double sumOfArray();
void PrintArray();
};
#endif /* VECTOR_H_ */
Does anyone know why it does not work? Thank you
Your Vector lacks a proper copy constructor.
Vector temp = *xp;
//NOT EQUAL TO:
//Vector temp;
//temp=*xp;
The above statement won't call operator=(const Vector &) even though there's an equal sign. The following line is correct and equivalent:
Vector temp(*xp);
The reason is that this is a copy initialization - temp is created and so a constructor must be called - in particular the copy constructor Vector(const Vector &). Which you did not explicitly declared and so a default one was used.
Then a shallow copy is made, temp and *xp then share the same array and when both their destructors get called the second one will try to delete already deleted memory - undefined behavior which triggers Visual Studio's debugger (at least in debug mode).
The solution is to do a proper deep copy - create a new array and copy its contents:
#include <algorithm> #Contains std::copy_n
Vector::Vector(const Vector& other)
{
name=other.name;
size=other.size;
//Creates a new array
array= new unsigned int[size];
//Copies the array contents
std::copy_n(other.array,size,array);
Boo=other.Bool;
}
Also this is a prime example of why not to use raw memory. I get that you are implementing custom vector and don't want to use std::vector for the array but at least use std::unique_ptr. If you would have just done that you wouldn't have to ask this question in the first place as the compiler would have complained and the debugger wouldn't have to do the compiler's job.

C++ Linked Lists with struct

I'm new in C++ and I have something to do with a linked list, and I don't know why it doesn't work, need help from a prof :O)
Here's my .h
#ifndef UnCube_H
#define UnCube_H
using namespace std;
class ACube{
public:
ACube();
struct Thecube;
private:
void PrintList();
};
#endif
My ACube.cpp
#include <iostream>
#include "ACube.h"
ACube::ACube(){
};
struct Thecube{
int base;
int cube;
Thecube * next ;
};
void ACube::PrintList(){
};
and finally my main.cpp
#include <cstdlib>
#include <iostream>
#include "ACube.h"
using namespace std;
int main()
{
ACube * temp;
temp = (ACube*)malloc(sizeof(ACube));
for (int inc=1; inc <=20 ; inc++){
temp->ACube->nombrebase = inc;
temp->cube = inc*inc*inc;
}
system("PAUSE");
return EXIT_SUCCESS;
}
Everything was working fine, but when I add these lines :
temp->ACube->nombrebase = inc;
temp->cube = inc*inc*inc;
I add error saying :
'class ACube' has no member named 'TheCube'
'class ACube' has no member named 'cube'
Can someone help me because I want to create my list and fill the cube with number.
Other thing I want to use THIS. in the print,
Maybe someone can teach me what's wrong and how to do it !
Thanks for any help
You don't need to have a struct inside your class.
#ifndef UnCube_H
#define UnCube_H
using namespace std;
class ACube{
public:
ACube();
int base;
int cube;
ACube * next ;
private:
void PrintList();
};
#endif
ACube.cpp
#include <iostream>
#include "ACube.h"
ACube::ACube(){
};
void ACube::PrintList(){
};
Also, this string is wrong:
temp->ACube->nombrebase = inc;
it should be just:
temp->base = inc;
Last but not least, this code doesn't create a linked list, because you don't do anything with the ACube::next pointer.
There are so many horrible problems in your code, I suggest you should learn more C++ knowledge before writing linked list.
1. What is nombrebase?
I think nobody can answer.
2. You must allocate C++ class by new key word instead of malloc.
new invokes not only allocation but also class constructor, while malloc allocates only.
3. Thecube should been defined inside ACube
Since the code in your main() refers the member cube in class Thecube, main() must know what it is.
4. The member next in class ACube is a pointer which points to what?
What does a pointer point to without initilization? You should initial it in constructor, and destroy it in destructor.
5. temp->ACube
ACube is a class type, you can access member object, but not a type.
6. Never using namespace into a header file
It would make the client of header file has name collision.
The following is the corrected code. Just no compile error and runtime error, but this is NOT linked list:
ACube.h
#ifndef UnCube_H
#define UnCube_H
class ACube{
public:
struct Thecube
{
int base;
int cube;
Thecube * next;
};
ACube();
~ACube();
Thecube *next;
private:
void PrintList();
};
#endif
ACube.cpp
ACube::ACube()
: next(new Thecube)
{
}
ACube::~ACube()
{
delete next;
}
void ACube::PrintList(){
}
main.cpp
#include <cstdlib>
#include <iostream>
#include "ACube.h"
using namespace std;
int main()
{
ACube * temp;
temp = new ACube;
for (int inc = 1; inc <= 20; inc++)
{
temp->next->base = inc; // <-- This is not linked list, you shall modify.
temp->next->cube = inc*inc*inc; // <-- This is not linked list, you shall modify.
}
system("PAUSE");
return EXIT_SUCCESS;
}

"undefined reference" to a template class function

I am writing a template class for an array of objects, call it arrayobjclass, which holds pointers to other objects, specifically to other arrays in my implementation. The arrays are implemented as objects as well, call them arrayclass.
Looking for compilation ready with minimal changes.
when I try to test my classes with the following line,
g++ main.cpp arrayclass.cpp arrayobjclass.cpp -o arrayobj
I get the following error:
/tmp/ccEpROXj.o(.text+0x17c): In function `main':
: undefined reference to `arrayobjclass<arrayclass, int>::arrayobjclass(int)'
/tmp/ccEpROXj.o(.text+0x1dc): In function `main':
: undefined reference to `arrayobjclass<arrayclass, int>::addelem(arrayclass*)'
collect2: ld returned 1 exit status
I really can't understand what is wrong. any help would be appreciated. the short relevant part of the code is below if it helps. THANKS IN ADVANCE!
This is what i have in main:
#include "arrayclass.h"
#include "arrayobjclass.h"
#include <iostream>
// 5 arrays of 10 maxsize each
#define MAXSIZE_array 10
#define NUMB_objs 5
using namespace std;
int main () {
//create a simple array as an arrayclass object
arrayclass * numbers1 = new arrayclass (MAXSIZE_array);
//array of objects to hold pointers to simple arrays as created above
arrayobjclass<arrayclass,int> * myobjs = new arrayobjclass<arrayclass,int> (NUMB_objs);
//fill up the simple array
int i;
for (i=0; i<10; i++) {
numbers1->addelem(i);
}
//add a pointer to the simple array in my array of objects
myobjs->addelem(numbers1);
}
//arrayobjclass.h
//declarations of an array of pointers to objects
template <class obj, class key>
class arrayobjclass {
private:
//obj * arrayptr;
obj * objarray [];
int maxsize;
int totalelem;
public:
arrayobjclass(int);
bool addelem(obj *);
};
//arrayobjclass.cpp
//implementation of arrayobjclass, array of pointers to objects
#include "arrayobjclass.h"
#include "arrayclass.h"
template <class obj,class key>
arrayobjclass<obj,key>::arrayobjclass (int size){
maxsize=size;
objarray = new obj[maxsize];
totalelem = 0;
}
template <class obj, class key>
bool arrayobjclass<obj,key>::addelem (obj * newobj) {
if (totalelem < maxsize ) {
objarray[totalelem] = newobj;
totalelem ++;
return true;
}
return false;
}
//arrayclass.h
class arrayclass {
private:
int * arrayptr;
int maxsize;
int totalelem;
public:
arrayclass(int);
bool addelem(int);
};
//arrayclass.cpp
#include "arrayclass.h"
arrayclass::arrayclass (int size){
maxsize=size;
arrayptr = new int[maxsize];
totalelem = 0;
}
bool arrayclass::addelem (int addval) {
if (totalelem < maxsize ) {
arrayptr[totalelem] = addval;
totalelem ++;
return true;
}
return false;
}
You can't put template declarations in .cpp files like that. Template declarations and implementation need to be visible in the same translation unit. Put template implementations in headers that you #include directly.
Define your function templates in the header. Compiler needs to see them.
Cheers & hth.,
Because templates are compiled when required, this forces a
restriction for multi-file projects: the implementation (definition)
of a template class or function must be in the same file as its
declaration. That means that we cannot separate the interface in a
separate header file, and that we must include both interface and
implementation in any file that uses the templates.
From http://www.cplusplus.com/doc/tutorial/templates/
For anyone passing by
you can also #include the implementation files in main
in main:
#include "arrayobjclass.h"
#include "arrayclass.h"
#include "arrayobjclass.cpp"
#include "arrayclass.cpp"