Can't create an instance of a class (no default constructor) - c++

Edit:
I've found the solution by myself. I'm sorry for this question, that wasn't fully understanble for You.
Okey, I have so much code in my program. I'm writing a tree with using a list,that I'm going to write. I can't use STL library.
30_Contaner.h:
#pragma once
#include "Container_5_30.h"
#include "Tree.h"
#include "List.h"
using std::cout;
using std::cin;
class Tree : public AbstractTree
{//Cathy
protected:
struct ListStruct{
void* key;
size_t size;
ListStruct* next;
};
//Iterator *globalIterator;
class List : public AbstractList{
public:
/*some code*/
List(MemoryManager& mem) :AbstractList(mem){//constructor
}
virtual ~List(){
}
//some functions
};
struct TreeStruct{
TreeStruct *parent;
//OneLinkedList* Children = new OneLinkedList;
List *Children;//error
void *elem;
size_t size;
int childIndex;
};
int numberOfElements;
bool globalBoolForRecursion;
//TreeStruct *TreeStructInstance = new TreeStruct;
List *ListInstance = new List;//error
public:
Tree(MemoryManager& mem) :AbstractTree(mem) {
//root = new TreeStruct;//root - корень дерева (элемент структуры Дерева)
numberOfElements = 0;//кол-во элементов в дереве пока что 0
}
//some functions
};
main.cpp:
#include "30_Container.h"
#include "30_Mem.h"
#include "Tree.h"
//********************************
void main(){
Mem mem(100);
Tree tree(mem);
//some code
}
30_Mem.h
#pragma once
#include "MemoryManager.h"
// Простейший менеджер памяти, использует ::new и ::delete
class Mem : public MemoryManager
{
public:
Mem(size_t sz) :MemoryManager(sz) {}
void* allocMem(size_t sz) { return new char[sz]; }
void freeMem(void* ptr) { delete[] ptr; }
};
All methods in AbstractTree,MemoryManager and AbstractList classes are virtual. I should get instance of List class inside Tree class. But, I have a problem: I don't have default constructor for List and, of course, when I write List *list = new List; I have an error. My teacher told me that I should use pointer to memory manager of tree, or address, may be. Do you have any idea?
P.S. I need 30_Mem.h in the future. I should be writing my own new

Instead of default initialization for ListInstance add initialization of ListInstance to constructor
Tree(MemoryManager& mem) :AbstractTree(mem), ListInstance(mem) {
//root = new TreeStruct;//root - корень дерева (элемент структуры Дерева)
numberOfElements = 0;//кол-во элементов в дереве пока что 0
}

Related

C++ Class internal struct dynamic allocation at its method

I've got some trouble in allocating (::operator new) the declared structs inside an class, at its method, as getting an non-nub-readable error:
error: cannot convert 'Automata::state*' to 'state*' in assignment
\
I have tried removing the "Automata::" declaration, placing "this->" and other random things, no success. Follows an example code;
#include <iostream>
#include <new>
class Automata{
public:
struct quintuple{
struct state *stateStr = NULL;
int stateSize = 0;
};
struct state{
struct symbol *symbolStr = NULL;
};
struct symbol{
char *state = NULL;
int stateSize = 0;
};
struct quintuple quintupleStr;
//Functions
void quintuple(int stateValidCounter);
};
void Automata::quintuple(int stateValidCounter){
this->quintupleStr.stateStr = (struct Automata::state *) ::operator new(sizeof(struct Automata::state) * stateValidCounter);
return;
}
int main(){
Automata automata;
automata.quintuple(5);
return 0;
}
/*
g++ -std=c++11 example.cpp -o example.out
example.cpp: In member function 'void Automata::quintuple(int)':
example.cpp:23:30: error: cannot convert 'Automata::state*' to 'state*' in assignment
this->quintupleStr.stateStr = (struct Automata::state *) ::operator new(sizeof(struct Automata::state) * stateValidCounter);
^
*/
Thank you for the attention.
Well, to be honest this is an sad tiredness event.
I would like to accept the #Passer By if he answers at.
The answer is simple as #Passer By comment at main section.
Be the code
#include <iostream>
#include <new>
class Automata{
public:
struct quintuple{
struct state *stateStr = NULL;
int stateSize = 0;
};
struct state{....};
struct quintuple quintupleStr;
//Functions
void quintuple(int stateValidCounter);
};
void Automata::quintuple(int stateValidCounter){
this->quintupleStr.stateStr = (struct Automata::state *) ::operator new(sizeof(struct Automata::state) * stateValidCounter);
return;
}
int main(){
Automata automata;
automata.quintuple(5);
return 0;
}
simply switch the struct code position..
class Automata{
public:
struct state{....};
struct quintuple{
struct state *stateStr = NULL;
int stateSize = 0;
};
struct quintuple quintupleStr;
....;
};
I still think the compiler error is a little misleading

Program Error, Due to the use of std::unique_ptr in VS2010?

I been writing a program in which, an array will dynamically grow when ever the max size is reach. I have used std::unique_ptr, but I'm not sure what is causing the error. I'm using VS2010.
The error is:
error C2027: use of undefined type 'DyArray::Impl' c:\program files (x86)\microsoft visual studio 10.0\vc\include\memory 2067
Here is the code
DyArray.h
#pragma once
#include <iostream>
#include <memory>
class DyArray
{
public:
DyArray(int IntialSize, int IncrementSize)
{
}
~DyArray()
{
}
void Insert(int Data);
void Set(int Position,int Data);
int Get(int Position);
void Print();
private:
DyArray(const DyArray&);
DyArray& operator=(const DyArray&);
struct Impl;
std::unique_ptr<Impl> m_Impl;
};
DyArray.cpp
#include "LinkedList.h"
#include <iostream>
struct DyArray::Impl
{
typedef struct
{
int* array;
size_t used;
size_t size;
}Array;
public:
Array* m_DyArray;
size_t m_InitalSize;
size_t m_IncrementSize;
Impl(Array* DyArray,int IntialSize,int IncrementSize):m_DyArray(DyArray),m_InitalSize(IntialSize),m_IncrementSize(IncrementSize)
{
m_DyArray->array = (int*)malloc(m_InitalSize * sizeof(int));
m_DyArray->used = 0;
m_DyArray->size = m_InitalSize;
}
~Impl()
{
free(m_DyArray->array);
m_DyArray->array = NULL;
m_DyArray->used = m_DyArray->size = 0;
}
void insertArray(int element)
{
if (m_DyArray->used == m_DyArray->size)
{
m_DyArray->size += m_IncrementSize;
m_DyArray->array = (int*)realloc(m_DyArray->array,m_DyArray->size*sizeof(int));
}
m_DyArray->array[m_DyArray->used++] = element;
}
void Display()
{
std::cout<<"\n";
for (int i = 0; i< m_DyArray->used;i++)
{
std::cout<<m_DyArray->array[i]<<" ";
}
}
};
void DyArray::Insert( int Data )
{
m_Impl->insertArray(Data);
}
void DyArray::Print()
{
m_Impl->Display();
}
Main.cpp
#include "DyArray.h"
#include <iostream>
void main()
{
DyArray dyarray(2,3);
dyarray.Insert(12);
dyarray.Insert(14);
dyarray.Insert(55);
dyarray.Insert(23);
dyarray.Insert(444);
dyarray.Insert(23);
dyarray.Print();
}
The destructor of your class needs to destroy the unique pointer, which in turn needs to delete the Impl it manages. It can only do that if Impl is a complete (i.e. fully defined) type.
Define the destructor in the source file, after the definition of Impl, not in the class definition.
You'll also need to define the constructor there, if you want it to create an Impl and initialise the pointer.

error C2512 but i have default constructor available

my code have error (error C2512: 'Node' : no appropriate default constructor available)
but i have default constructor why ???
my error location commented in code Please help me
Node.h
#pragma once
#include "stat.h"
#include "Automata.h"
#include <cstdlib>
class Node
{
friend class Automata;
friend class stat_a;
friend stat_a* makeauto(char *str);
friend int main();
private:
stat_a* mess;
char data;//harfi ke ba in masir estefadeh mishe :)
Node *next;//node badi dar araye node ha class stat_a :)
public:
Node()
{
mess = NULL;
next = NULL;
};
};
stat.h
#pragma once
#include "Node.h"
#include <iostream>
using namespace std;
class stat_a
{
friend class Automata;
friend class Node;
friend int main();
private:
bool is_final_stat_a; //aya final stat_a hast ???
int stat_a_num; //shomareh halat 0,1,2,...
Node *last; //akharin node dar araye node haye neshan dahande masir
Node *first; //Avalin node dar araye node haye neshan dahande masir
public:
void add(char d,stat_a * a)//ezafeh kardan masiri ke ba estefadeh
{ //az harf (char d ) be halat (stat_a a) miravad
if(first == NULL)
{
first = new Node;//error is here
first->data = d;
first->mess = a;
last=first;
}
else
{
last->next = new Node ;//erorr is here
last=last->next;
last->data=d;
last->next=NULL;
last->mess=a;
}
};
/***********************************************************************/
void print()
{
cout<<stat_a_num<<"========> is final_stat_a : "<<is_final_stat_a<<endl;
Node *a;
a=first;
while(a != NULL)
{
cout<<"========> By '"<<a->data<<"' go to stat "<<a->mess->stat_a_num<<endl;
a=a->next;
}
};
stat_a()
{
last=NULL;
first=NULL;
is_final_stat_a=false;
};
~stat_a(void);
};
I have default constructor available why error
It's a classical example of circular dependency. The header file Node.h depends on the header file stat.h which depends on Node.h and so on.
Since you only declare a pointer variable of type stat_h in Node, you don't need to include the header file for that, it's enough to declare the class stat_a:
#pragma once
#include "Automata.h"
#include <cstdlib>
class stat_a; // Declare the class, so the compiler know there's a class by this name
class Node
{
// ...
private:
stat_a* mess; // Works because you're only declaring a pointer
// ...
public:
// ...
};
Then in the stat.h header when you include Node.h there is no longer a circular dependency.
Replace
Node();
{
mess = NULL;
next = NULL;
}
with
Node()
{
mess = NULL;
next = NULL;
};

VC++ debug assertion failed on program exit

I'm trying to create a linked list class template (Yes, I know there's one in the c++ library but I wanted to create my own for fun). I've traced through the code and all seems well until the program exits.
Here's the used code:
list.h:
#ifndef LIST_H
#define LIST_H
#include "misc.h"
template <typename T> class CList {
private:
class CNode {
friend CList;
private: T data;
CNode* next;
public: CNode() : next(NULL) {}
~CNode() { delete [] next; }
};
private: int length;
CNode* first;
public:
CList() : length(0), first(NULL) {}
CList(int i_length) : first(NULL) {
int i;
CNode* cur = NULL;
CNode* prev = NULL;
if (i_length < 0) length = 0;
else length = i_length;
for (i=0;i<length;i++) {
// allocate new CNode on heap
cur = new2<CNode>();
// attach preceding CNode pointer
if (prev) prev->next = cur;
else first = cur;
prev = cur;
}
}
~CList() { delete first; }
};
misc.h
#ifndef MISC_H
#define MISC_H
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
inline void terminate( const char* message, int code ) {
printf("\n\n%s\n\n",message);
system("pause");
exit(code);
};
template <typename T> inline T* new2() {
T* ret = new T;
if (!ret) terminate("Insufficient Memory",-2);
return ret;
}
template <typename T> inline T* new2(int num) {
if (num <= 0) terminate("Invalid Argument",-1);
T* ret = new T[num];
if(!ret) terminate("Insufficient Memory",-2);
return ret;
}
#endif
main.cpp
#include <stdio.h>
#include <stdlib.h>
#include "../Misc/misc.h"
#include "../Misc/list.h"
int main(int argc, char* argv[]) {
//CList<int> m;
CList<int> n(5);
system("pause");
return 0;
}
Here is what the variable "n" looks like at the breakpoint just before "return 0;".
http://s20.beta.photobucket.com/user/marshallbs/media/Untitled_zps52497d5d.png.html
Here's the context in which the error occurs. Unfortunately at this point I can no longer view the variable "n" on the watch list.
_mlock(_HEAP_LOCK); /* block other threads */
__TRY
/* get a pointer to memory block header */
pHead = pHdr(pUserData);
/* verify block type */
_ASSERTE(_BLOCK_TYPE_IS_VALID(pHead->nBlockUse));
There is no error when I use the default constructor for my list. I don't understand what's going on as the memory release process should stop when it reaches the fifth CNode object which has a null "next" pointer. It acts as though it's trying to releasing an invalid non-null pointer but I don't see how this can happen.
I built and ran (from the debugger) the code as-is and got no assertion failures. In fact, there is no memory deallocation at all because CList doesn't have a destructor (didn't you post the complete code?).
One problem is that you allocate next using new and free it using delete[]. This is undefined behaviour.
Allocation:
cur = new2<CNode>(); // new2 uses `new' and not `new[]'
Deallocation:
~CNode() { delete [] next; }
Replace the latter with delete next;.

Problems pertaining to compilation of C++ application in g++ (probable cause #ifndef)

I am trying to build a Linked list application using C++ programming language & features such as inheritance etc.
I have split the interface & implementation in different files but not able to compile.
Below are the list of files
Interface files :- node.h , abstractList.h , singleLinkedList.h
Implementation files: singleLinkedList.cpp
node.h
#ifndef NODE_H
#define NODE_H
#include <iostream>
struct nodeType {
int data;
struct nodeType *next;
}listNode;
#endif
abstractList.h
#ifndef ABSTRACT_LIST_H
#define ABSTRACT_LIST_H
#include <iostream>
#include "node.h"
#include "singleLinkedList.h"
class abstractList {
public:
virtual ~abstractList();
virtual bool isEmpty(Node* ) = 0;
virtual int get(const int&) = 0;
virtual int indexOf(const int& ) = 0;
virtual Node insert(const int& , const int& ) = 0;
virtual void delete(const int& ) = 0;
};
#endif
singleLinkedList.h
#ifndef SINGLE_LIST_H
#define SINGLE_LIST_H
#include <iostream>
#include "node.h"
#include "abstractList.h"
class singleLinkedList : public abstractList {
public:
singleLinkedList();
~singleLinkedList();
Node populateList( );
private:
void checkIndex();
int data;
Node head;
};
#endif
So far i have just coded the populateList() function in the implentation file, here goes the implementation file.
singleLinkedList.cpp
#include <iostream>
#include "node.h"
#include "singleLinkedList.h"
#include "abstractList.h"
Node singleLinkedList :: populateList()
{
Node temp;
int data;
temp = head;
char ch;
std::cout<<"Enter Data? (y/n) " << std::endl;
std::cin>>ch;
while(ch == 'Y' || ch == 'y')
{
std::cout<<"Enter the data that you would like to store.\n"<<std::endl;
std::cin>>data;
temp = new Node();
temp->data = data;
temp->next = head;
head = temp;
std::cout<<"Enter more data?"<<std::endl;
std::cin>>"\n">>ch;
}
return temp;
}
When i give g++ -c singleLinkedList.cpp , i am getting lot of errors. I am pretty sure i have done something stupid. Can anyone please pin point my error?
EDIT: Error Log With specfic issues.
struct nodeType {
int data;
struct nodeType *next;
}listNode;
virtual listNode *insert();
Is the above statement correct?
Thanks
Kelly
delete is a keyword in C++, you can't use it as a method name. You need to use a different name here:
class abstractList {
public:
//...
virtual void delete(const int& ) = 0;
//-----------^^^^^^ rename this.
};
The problem is in your typedef:
typedef listNode *Node;
means that all instances of Node will essentially replaced by listnode*
temp = new Node();
actually reads
temp = new listnode*();
But new Foo() would return a Foo* (because new returns a pointer to memory allocated for an object), meaning that new listnode*() would return a listnode**. temp being a listnode* has no Idea what a listnode** is and complains.
what you want to do is:
Node temp = new listnode();
or forget the typedef altogether:
listnode* temp = new listnode();