In this program, I m creating an object and then just destroying the object using destructor..and I'm using a static variable as a counter...the program compiles successfully but I m not getting any output...and when I try to run it on code block I get a message "code blocks stopped working"..I m at windows 10 with gnu GCC compiler.
#include <iostream>
using namespace std;
class ashish
{
int *age;
public:
static int classm;
ashish()
{
*age=10;
classm++;
}
~ashish(){
cout<<"this going to destroy the object";
delete age;}
};
int ashish::classm=0;
int main()
{
ashish *blast;
blast=new ashish();
cout<<ashish::classm<<"chec"<<endl;
delete blast;
return 0;
}
You're not allocating memory for age, like you did with blast (blast = new ashish();)
Related
main:
#include <iostream>
#include "common.h"
#include "squares.h"
#include "board.h"
using namespace std;
int Board::board_length=8;
int main()
{
Board *tabla=new Board();
tabla->printBoard();
}
board.h :
#ifndef BOARD_H
#define BOARD_H
#include "squares.h"
class Board
{
static int board_length;
Square boardSquares[board_length][board_length];
public:
Board();
void printBoard();
};
error line 8 in board.h
C:\c++ projects\CHESS-P3\board.h|8|error: array bound is not an integer constant before ']' token|
As the error message indicates, board_length is not a constant value. To fix that, change the line
static int board_length;
in board.h to
static const int board_length = 8;
and remove the line
int Board::board_length=8;
from your main file. This should compile, but I cannot tell for sure, since you did not provide a minimal, reproducible example.
Bonus: To avoid a memory leak you should also change
Board *tabla=new Board();
tabla->printBoard();
in main just to
Board tabla;
tabla.printBoard();
Since you do not seem to be passing the Board instance around, there is no need to use a pointer here.
As a general rule of thumb: Whenever there is a new somewhere, there also needs to be a corresponding delete. Otherwise your pogram may leak memory. While this is no big deal for a small, short-running example program, it can become a serious issue for a program that runs for a long time.
This is a nice use case for an int template:
board.h
template<int _board_length>
class Board
{
static const int board_length = _board_length;
int boardSquares[_board_length][_board_length];
public:
Board(){};
void printBoard(){};
};
main.cpp
...
constexpr int BL=8;
//odr declare the static member if it matters
template<>
const int Board<BL>::board_length;
int main() {
Board<BL> tabla;
tabla.printBoard();
}
That way, the actual dimensions of the array are defined in the main and not in the include file where the class is declared, and all the methods in Board can know the actual size.
Well, I wrote a simple code to check the possibility of creating objects using 'new' operator. When I was trying to compile the code, the MS Visual Studio threw the error like this: " Error: Unable to open file C:\Users...\test1\Debug\main.obj. Error code = 0x80070002.Error: Could not find 'C:\Users...\test1\Debug\main.obj'. test1.exe was built with /DEBUG:FASTLINK which requires object files for debugging.
What is going on? Please help.
Code:
#include <iostream>
class czlowiek {
int wiek;
char plec;
czlowiek();
czlowiek(int Wiek, int Plec);
};
czlowiek::czlowiek(int Wiek, int Plec) {
wiek = Wiek;
plec = Plec;
}
int main()
{
czlowiek *first;
first = new czlowiek();
delete first;
std::cin.get();
return 0;
}
The code you posted will not link:
The constructor czlowiek() doesn't have an implementation.
Both constructors are private (in classes members and methods are private by default).
As warning, you are assigning a int to a char (plec).
I am new c++ so forgive me to be asking this question. I created a project and run it the first time, it is successful. But when i start another project and i added 4 classes to it (you can see from the tabs) and the main.cpp is unable to run. I am confused as the codes are exactly the same in both projects.
Run Successful:
Success
Build Successful but run failed:
Run Failed
What are the solutions to solve this problem?
Do i have to post codes of all my classes? (there are 8 files)
student.h:
#ifndef CLSSTUDENT_H
#define CLSSTUDENT_H
#include <string>
#include <iostream>
using namespace std;
class clsStudent {
protected:
string name;
string student_no;
string program;
public:
clsStudent(string n, string sn,string prog );
virtual void displayStudentDetails();
};
student.cpp
#include "TutorialClass.h"
void TutorialClass::addStudent(clsStudent std)
{
_students.push_back(std);
}
int TutorialClass::getStudentCount()
{
return _students.size();
}
void TutorialClass::display()
{
}
#endif /* CLSSTUDENT_H */
I open up a new project and added only this class. It is unable to run as well. What is the problem in the codes?
It seems that your program only fails to run when it's compiled with other files. My bet is that in these files you've got buggy code that is running before main() gets to run.
This can happen in cases like this:
int f() {
throw; // bam! Uncaught exception;
}
int x = f(); // this runs before main()
Or this:
class C {
C() {
cout << "This runs before main() too!" << endl;
}
};
C my_c; // calls constructor
In both cases: code was executed before main(). You want this because you want your global variables to be initialized before running main(). If this initialization code manages to crash the program via a segfault or an exit() call or throwing some exception which isn't caught? You've got a crashed program before it ever even gets the chance to run.
This has been driving me nuts for a long time now. I have followed every tutorial I could find on the internet (here are couple examples[ [1], [2] of the maybe half dozen good ones found via Google search), and still no clear explanation. Although it seems it must be something fairly simple as that lack of a documented explanation implies that it's something most people would take for granted.
How do I load a custom module into Lua?
On the advice of questions like this one, I have written a module that builds a shared library with the expectation that I would be able to load it through a require call. However, when I do that I get undefined symbol errors, despite those exact symbols appearing in the list from the command nm -g mylib.so.
Those two tutorials I linked before aim to create executables that look wrappers of the *.lua file. That is, the built *.exe file should be called to run the Lua program with the custom module.
I understand that these types questions are asked here fairly frequently (as noted in this answer), but I am still at a loss. I tried some of the binding packages (Luabind and OOLua), but those didn't work out great (e.g. my earlier question--which I did ultimately figure out, sort of).
I have implemented a class in C++
I have wrapped the constructors, destructors, and functions with thunks
I have built it errorless-ly as a shared library
Yet no matter what I get undefined symbol: ... errors when I try to load it as mod = require('mylib.so'). How do I do this?
Working Example of a Library of Functions
For the record, just registering a basic function works fine. The below code, when built as libluatest.so, can be run in Lua using the commands:
> require('libluatest')
> greet()
hello world!
libluatest.cpp
extern "C"
{
#include <lualib.h>
#include <lauxlib.h>
#include <lua.h>
}
#include <iostream>
static int greet(lua_State *L)
{
std::cout << "hello world!" << std::endl;
return 0;
}
static const luaL_reg funcs[] =
{
{ "greet", greet},
{ NULL, NULL }
};
extern "C" int luaopen_libluatest(lua_State* L)
{
luaL_register(L, "libluatest", funcs);
return 0;
}
Failing Example of a Class
This is what I am stuck on currently. It doesn't seem to want to work.
myObj.h
#include <string>
class MyObj
{
private:
std::string name_;
public:
MyObj();
~MyObj();
void rename(std::string name);
};
myObj.cpp
extern "C"
{
#include <lualib.h>
#include <lauxlib.h>
#include <lua.h>
}
#include <iostream>
#include "myObj.h"
void MyObj::rename(std::string name)
{
name_ = name;
std::cout << "New name: " << name_ << std::endl;
}
extern "C"
{
// Lua "constructor"
static int lmyobj_new(lua_State* L)
{
MyObj ** udata = (MyObj **)lua_newuserdata(L, sizeof(MyObj));
*udata = new MyObj();
luaL_getmetatable(L, "MyObj");
lua_setmetatable(L, -1);
return 1;
}
// Function to check the type of an argument
MyObj * lcheck_myobj(lua_State* L, int n)
{
return *(MyObj**)luaL_checkudata(L, n, "MyObj");
}
// Lua "destructor": Free instance for garbage collection
static int lmyobj_delete(lua_State* L)
{
MyObj * obj = lcheck_myobj(L, 1);
delete obj;
return 0;
}
static int lrename(lua_State* L)
{
MyObj * obj = lcheck_myobj(L, 1);
std::string new_name = luaL_checkstring(L, 2);
obj->rename(new_name);
return 0;
}
int luaopen_libmyObj(lua_State* L)
{
luaL_Reg funcs[] =
{
{ "new", lmyobj_new }, // Constructor
{ "__gc", lmyobj_delete }, // Destructor
{ "rename", lrename }, // Setter function
{ NULL, NULL } // Terminating flag
};
luaL_register(L, "MyObj", funcs);
return 0;
}
}
Compiled into libmyObj.so using a simple CMake build with C++11 standard flags on.
Error
> require('libmyObj')
error loading module 'libmyObj' from file './libmyObj.so':
./libmyObj.so: undefined symbol: _ZN5MyObjC1Ev stack traceback: [C]:
? [C]: in function 'require' stdin:1: in main chunk [C]: ?
I am dealing with Lua 5.1 on Ubuntu 14.04.
I am wondering if it has something to do with the mix of C and C++...
It seems that you do not implement:
MyObj() ; ~MyObj();
and be careful with luaopen_* function, since module name is myObj, function name should be luaopen_libmyObj.
So, this problem, for some reason it shows me this error (ubuntu, terminal, g++). I searched the net and didn't show anything similar to mine. The code is (gfdz.cpp)
#include <iostream>
#include <string>
using namespace std;
struct dynmass
{
unsigned long int vm; //вместимость
unsigned long int el; //количество элементов
};
int *i,*q;
void create()
{
dynmass a;
a.vm = 0;
a.el = 0;
i = new int[0];
extern "a"
{
void push();
void remuve();
int kolichestvo();
int vmestimostb();
int main;
};
}
What you have there is a language linkage specification. And within it, you have a bunch of function declarations.
A language specifications can only appear in namespace scope. Yours is in the block scope, so that's what's wrong with it. Also, "a" language linkage is not supported by standard c++ so you may need to consult your compiler manual to find out if it's supported.