Didn't mean to fault the compiler; I realize my code is pretty much self-destructive. I now see how delete
works with objects, though :).
Many thanks.
Didn't mean to fault the compiler; I realize my code is pretty much self-destructive. I now see how delete
works with objects, though :).
Many thanks.
I mean, the destructor is executed twice. Once on delete this
and again on delete ptr
.
My question is, why is the destructor even called on delete ptr
since ptr
is pointing to an object that doesn't exist? If the object doesn't exist, how can the destructor be called a second time?
I've been messing around with c++ and attempting to fully understand certain behaviors. Given the following program:
#include <iostream>
class Test {
public:
Test();
~Test();
void func();
};
Test::Test()
{
std::cout << "Constructor" << std::endl;
}
Test::~Test()
{
std::cout << "Destructor" << std::endl;
}
void Test::func()
{
std::cout << "Deleting this..." << std::endl;
delete this;
std::cout << "Deleted this" << std::endl;
}
int main(int argc, char **argv)
{
Test* ptr;
ptr = new Test;
ptr->func();
delete ptr;
std::cin.get();
return 0;
}
I do realize one would almost never have a reason for "delete this." However, the odd thing I noticed is when the program reaches "delete ptr," it spits out an error (as it should), but when I view the console window it shows "Destructor" on the last line.
The output I am getting is this:
Constructor
Deleting this...
Destructor
Deleted this
Destructor
I am curious as to why "Destructor" outputs twice; I would think deleting an object that doesn't exist would cause the error prior to entering the destructor. I would assume (one should probably not assume when one is a newbie) the destructor can be called as it exists in the code, and it is only when the class itself finally dies (on the closing brace of the destructor) that it gives the error when it tries to delete the specific instance. I am still curious as to why the error is not chucked (or thrown, if you prefer) as soon as delete is called …
It appears you still have three functions to code and potential logic errors to debug, but that should get rid of your compiler errors for the moment.
'Char' is not a valid C++ type.
'Num' function does not match its prototype (see lines 23 and 58).
'Num', if ever executed, will never execute lines 66-77; enclose your 'if' statements in braces and you should find the answer.
Match all opening braces ( '{' ) with closing braces ( '}' ).
Should help clear some of your compiler errors.
When you add the semicolon, that is the scope of the loop. while (true) {this stuff executes}
while (true); {this stuff never executes}
The semi-colon is terminating the scope of the loop before it executes the stuff inside the braces. The same applies for 'if' and 'for'.
Try changing SDL_SURFACE to SDL_Surface.
Also, for ease of use, you might try dumping the SDL headers into your IDE's header folder - a wee easier than typing that long string per source file.
sqrt() requires a double, float, or long double as a parameter. Judging by your variable name, you're attempting to pass an int to sqrt(). Try using static_cast to convert it to a double like so:
cout << "The square root of " << num << " is " << sqrt(static_cast<double>(num)) << endl;
Thanks for the help. I always assumed since the constructor isn't virtual, the destructor wouldn't have to be either. The memory leaks are gone :)
I'm having several difficulties with memory leaks in a program (I've been using "Visual Leak Detector" to check for memory leaks). I've simplified the code to the following:
#include "vld.h"
#include "vldapi.h"
#include <string>
#include <vector>
class BaseFoo {
public:
BaseFoo() {}
~BaseFoo() {}
};
class ButtonFoo {
public:
void setText( std::string text ) { _text = text; }
private:
std::string _text;
};
class InheritedFoo : public BaseFoo {
public:
InheritedFoo();
private:
ButtonFoo buttons[4];
};
InheritedFoo::InheritedFoo()
{
ButtonFoo button;
for( unsigned int i = 0; i < 4; i++ ) {
buttons[i] = button;
}
buttons[0].setText( "NO MORE MEMORY LEAKS" );
buttons[1].setText( "I DONT LIKE YOU ANYMORE" );
buttons[2].setText( "I DONT WANT YOU ANYMORE" );
buttons[3].setText( "GO AWAY" );
}
int main( int argc, char **argv )
{
std::vector<BaseFoo*> modules;
modules.push_back( new InheritedFoo() );
for( unsigned int i = 0; i < modules.size(); ++i ) {
delete modules[i];
}
}
I suspect 'modules' is the source of the memory leak. Why is the vector leaking memory? And is there a way around it?
Rather than having YesorNofunc() call another function, it would probably be easier to have it return int. You could declare two constants (or use #define) YES and NO. Then whenever you need a yes or no answer, you could use an if/else statement:
const int YES = 1;
const int NO = 2;
if( YesorNofunc() == YES ) {
// ... do yes stuff, call a function or w/e ...
}
else {
// ... do no stuff ...
}
You might want to rename your function too; having "func" on the end of a function name doesn't make much sense. It should be obvious a name is a function. If you need "func" to remind yourself it is a function and not a variable, something is wrong with your naming.
After creating the Win32 Console Application project, there should be a window that says "Win32 Application Wizard". Click "next" and click the "Empty Project" checkbox.
Win32 Console Application.
Under "Build", click "Build Solution", or just hit F7.
If there is no "Build" in the menu, then you need to create a project first. Click File->New->Project.
I think your problem is with cin. Using cin >> somevar
followed by getline() will cause a few problems. Putting cin.ignore( 1024, '\n' )
before getline usually works for me. You will probably want to read http://www.daniweb.com/forums/thread90228.html.
Keep the code short and sweet!
As much as we don't care, people insist on posting pages and pages of irrelevant code. Keep the code as short as possible. If the code isn't short, make it short by cutting out as much irrelevant code as possible. Ideally, we expect you to write a small test program that exhibits the problem you're having.
The benefit of this is twofold. First, you might end up solving the problem yourself. Second, if you can't solve the problem yourself, there's less code that we have to look at and the problem is more likely to jump out at us.
Try shrinking your code to what is relevent to your problem. No one is going to try reading through ~700 lines.
should better look likebool isPrime (int variable) { return variable > 2 && variable % 2 == 1; }
That needs to be == 0
instead of == 1
.
Your problem with the "ambiguous overload for operator in cin >> variable" is caused because variable was declared as const. When you declare something as a const, it cannot be changed. Since a const variable cannot be changed, cin cannot write any data to it.
You'll also have a problem with line 6, because "number" is an undeclared identifier. It doesn't make much sense for i or j to be const anyway. The only output is i and j, and since they are const, the output will always be the same.
You might also want to change the name of "isPrime" to "isEven".
You don't need to declare Q and q as chars to use 'Q' and 'q'. You also have an unreferenced variable (ie, a variable you declared but never used).
Take a closer look at the logic in the while loop. It won't execute as you intended. It will always be true, so the program will never break out of it.
Take a look at first line of code in do_next_op(); does it make sense for it to be there?
You also forgot to get some additional input from the user, which is why the program prints out garbage data (if you're using VC++, you'll get a run-time error).
As I was busy inlining some of my functions, I was wondering if it is really necessary to inline anything. Doesn't the compiler automatically inline stuff, or do I have false memories? And if the compiler does inline stuff for me, would it be best to let it do its job or should I mess up something by doing it myself?
The reason I thought of the first question is because I can't get my now-inlined functions to work. A quick example:
test.cpp
#include <iostream>
#include <string>
#include "test.h"
void main()
{
std::cout << getString();
std::cin.get();
}
test2.cpp
#include "test.h"
inline
std::string getString()
{
return "Beam me up, Scotty!";
}
test.h
#ifndef TEST_H
#define TEST_H
#include <string>
std::string getString();
#endif
This generates the error:
test.obj : error LNK2019: unresolved external symbol "class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl getString(void)" (?getString@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) referenced in function _main
C:\w\e\Projects\test\Debug\test.exe : fatal error LNK1120: 1 unresolved externals
Removing the inline will make the program work.
Below is my declaration a Class in window form application, and the error was stated as below:
CLoadObj^ g_LoadObj = gcnew CLoadObj;
I believe you mean CLoadObj* g_LoadObj = gcnew CLoadObj;
I think the problem is with the constructor. You either need to add parameters matching the class constructor in the line Mortgage myMortgage();
or make a default constructor with no parameters.
It's the same problem as this:
#include <iostream>
using namespace std;
class MyClass {
public:
MyClass( int a );
int num;
};
MyClass::MyClass( int a )
{
num = a;
}
int main()
{
MyClass myclass();
myclass.num = 5; // Error
cout << myclass.num; // Error
return 1;
}
You can fix it by creating another constructor MyClass();
, or by changing MyClass myclass();
to MyClass myclass( 5 );
.
Well, I messed around with my code for a few hours, and I discovered that it wasn't actually a problem with the vector (as always, I blamed the other code first). The problem is by the time the program gets to the Font destructor, the TTF library has already quit. This is really quite annoying, since I closed the TTF library using atexit().
The problem now is getting the class destructor to run before the atexit stuff. With the code:
#include <iostream>
using namespace std;
class myClass {
public:
myClass() { cout << "Constructor" << endl; }
~myClass() { cout << "Destructor" << endl; }
};
myClass loser;
void func()
{
cout << "Func" << endl;
}
int main()
{
atexit( func );
return 1;
}
the output will be "Constructor Func Destructor". Does anybody know a [non-messy] way around this?
Remove #include "stdafx.h"
.
For file operations, look up the fstream header. The basic code looks something like this:
#include <fstream>
using namespace std;
int main()
{
fstream file;
file.open( "whatever.whatever" );
// Check to make sure the file is open with file.is_open()
// Read data line by line using file.getline(); works just like cin.getline()
// You can use file.eof() to check if you're at the end of the file (eof stands for end of file)
file.close();
return 0;
}
For your second question, you should probably read http://www.cplusplus.com/doc/tutorial/arrays.html
Try re-examining the flow of your program. Think as the compiler: go line by line and ask "What is happening here?"
If you do not understand something in your code, I recommend you look it up on www.cplusplus.com
The problem with that approach is how my function works. Each time the program needs to display text, it calls renderText(). Loading a font takes my computer about 3 milliseconds, and I'm already worried about SDL going too slow. Thus, I opted to use a vector array of class 'Font', since vectors are easiest when it comes to expanding arrays, and each class can automatically close the TTF_Font* variable, plus I can use previously loaded fonts and I could do it all without the hassle of dynamic memory. Since no other function has access to the vector, I can't delete the class pointers in the vector at the end of the program.
Your response did get me thinking about some possible alternatives. I could make another flag to put in the flags parameter that would let the function know it has to delete the fonts; I could make a class which would contain the vector of pointers to the 'Font' class, making use of the class destructor to delete the vector; or I could give a void function access to the vector, so I could use atexit() to delete the vector (probably wouldn't work as the vector would probably be removed from memory prior to the atexit() call).
If you have any other ideas, please let me know, as mine kinda suck. I would still like to know why the vector is acting as it is, so I can avoid this in the future.
I used resize instead of push_back because push_back requires that you put in a value. If I were to declare another instance of Font, set all the variables, then use that in push_back(), it is my understanding that the pointers from both instances would point to the same object. Since the temporary class would call the destructor at the end of the if statement it would delete the object, leaving me with a dangling pointer. Alternatively, I could do:
Font temp;
fonts.push_back( temp );
It does work, but it just seems odd. Of course, I could be wrong cause I'm no expert on vector arrays.
I have a vector array of a class that's giving me some crap. I would beat it up, but that might result in some innocent circuits getting damaged.
Class:
class Font {
public:
Font();
~Font();
int style;
int ptSize;
std::string name;
TTF_Font *font;
};
Font::Font()
{
style = TTF_STYLE_NORMAL;
ptSize = 0;
name = "";
font = NULL;
}
Font::~Font()
{
// Access violation
TTF_CloseFont( font );
}
Code:
std::vector<Font> fonts;
SDL_Surface *renderText( std::string fontName, int ptSize, std::string text, const SDL_Color *textColor, const SDL_Color *backroundColor, int flags )
{
// cut
if( fontElement == -1 ) {
std::string fileName = "c:\\windows\\fonts\\" + fontName;
// class constructor called here
fonts.resize( fonts.size() + 1 );
fontElement = fonts.size() - 1;
fonts[ fontElement ].ptSize = ptSize;
fonts[ fontElement ].name = fontName;
fonts[ fontElement ].font = TTF_OpenFont( fileName.c_str(), ptSize );
if( fonts[ fontElement ].font == NULL ) {
return NULL;
}
if( fontStyle != TTF_STYLE_NORMAL ) {
fonts[ fontElement ].style = fontStyle;
TTF_SetFontStyle( fonts[ fontElement ].font, fontStyle );
}
// class destructor called here
}
// cut
// no error here
if( flags & FH_BLENDED ) {
return TTF_RenderText_Blended( fonts[ fontElement ].font, text.c_str(), fgColor );
}
else if( flags & FH_SHADED ) {
return TTF_RenderText_Shaded( fonts[ fontElement ].font, text.c_str(), fgColor, bgColor );
}
else if( flags & FH_SOLID ) {
return TTF_RenderText_Solid( fonts[ fontElement ].font, text.c_str(), fgColor );
}
return NULL;
}
The problem is that right after the if statement the class destructor is called. Oddly enough, when I use …
Here's the code I wrote for retrieving stuff in the buffer. It works at first, but later on it keeps reading the same thing over and over. From what I gathered on MSDN, recv should flush the buffer each time it is read, but it is not doing that. Also, I don't think this matters, but this is run in a seperate thread.
int dataRetrieval( void *data )
{
while( !quit ) {
if( mainCanReadBuffer == false ) {
char tempBuffer[100];
int error = recv( sock, tempBuffer, 100, 0 );
int bytes = 0;
while( tempBuffer[bytes] != '\0' && bytes < 100 ) {
bytes++;
}
delete [] buffer;
buffer = new char[bytes + 1];
for( int i = 0; i <= bytes; i++ ) {
buffer[i] = tempBuffer[i];
}
mainCanReadBuffer = true;
}
}
return 0;
}
I send data like this:
stringstream infoHolder;
infoHolder << "coord" << players[myRect].y << "\0";
send( sock, infoHolder.str().c_str(), sizeof( infoHolder.str().c_str() ) * infoHolder.str().length(), 0 );
> but I've been having several problems with winsock.
Such as?
The largest problem is that winsock appears to be appending data to the end of the buffer, in which case, how am I supposed to read the end of the buffer? It is also appending garbage data, which I am positive I never sent.
If it's because your programs are crashing, or have odd behaviour?
Aside from the buffer problem, there's no crashing or odd behavior.
Or is there some aspect of network functionality you deperately need?
In which case, you should state your requirements.
I just need something that will send and receive data. When I used to program Visual Basic, winsock worked perfectly, but not so with C++.
I'm creating a multiplayer game using winsock, but I've been having several problems with winsock. I've been searching for an alternative to it, but I haven't found anything. If anyone could point me to something I could use in place of winsock (a free something), I would greatly appreciate it.
Thanks, these are much better ways than what I had before.
I've been getting an "Access Violation" error while running this program:
#include "SDL/SDL_ttf.h"
class Font
{
private:
TTF_Font *font;
public:
Font()
{
font = TTF_OpenFont( "c:\\windows\\fonts\\cour.ttf", 20 );
}
~Font()
{
TTF_CloseFont( font ); //Access violation
}
};
int main( int argc, char *args[] )
{
if( TTF_Init() < 0 )
{
return 1;
}
Font thing;
TTF_Quit();
return 0;
}
Apparently, calling TTF_Quit before TTF_CloseFont will cause the error. Is there any easy way around this?
I have a header file causing me several errors. It contains a class definition, then I have a *.cpp file with the function definitions.
Header:
#ifndef DOT_H
#define DOT_H
#include "SDL/SDL.h"
#include <vector>
class Dot
{
private:
int x, y;
int xVel, yVel;
vector<SDL_Rect> box;
bool check_collision( vector<SDL_Rect> &A, vector<SDL_Rect> &B );
void shift_boxes();
public:
Dot( int newX, int newY );
int get_x();
int get_y();
vector<SDL_Rect> &get_rects();
void handle_input( SDL_Event *trigger );
void move( vector<SDL_Rect> &rects );
};
#endif
The *.cpp code is a bit lengthy, so I won't post it unless it is needed. Anyway, here's the errors I'm getting:
c:\documents and settings\compaq_administrator\my documents\visual studio 2008\projects\sdl_tutorials\per pixel collision\per pixel collision\dot.h(12) : error C2143: syntax error : missing ';' before '<'
c:\documents and settings\compaq_administrator\my documents\visual studio 2008\projects\sdl_tutorials\per pixel collision\per pixel collision\dot.h(12) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\compaq_administrator\my documents\visual studio 2008\projects\sdl_tutorials\per pixel collision\per pixel collision\dot.h(12) : error C2238: unexpected token(s) preceding ';'
c:\documents and settings\compaq_administrator\my documents\visual studio 2008\projects\sdl_tutorials\per pixel collision\per pixel collision\dot.h(14) : error C2061: syntax error : identifier 'vector'
c:\documents and settings\compaq_administrator\my documents\visual studio 2008\projects\sdl_tutorials\per pixel collision\per pixel collision\dot.h(23) : error C2143: syntax error : missing ';' before '<'
c:\documents and settings\compaq_administrator\my documents\visual studio 2008\projects\sdl_tutorials\per pixel collision\per pixel collision\dot.h(23) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
c:\documents and settings\compaq_administrator\my documents\visual studio 2008\projects\sdl_tutorials\per pixel collision\per pixel collision\dot.h(23) : error C2238: unexpected token(s) preceding ';'
c:\documents and settings\compaq_administrator\my documents\visual …
Thanks for the help guys. I knew it was something stupid.
struct SDL_Rect is define by SDL.h
so if you want to use it just include the header...
anyway SLD need main to have int main(int argc, char **argv)
this compile for me ;)#include <SDL/SDL.h> #define CLIP_MOUSEOVER 0 #define CLIP_MOUSEOUT 1 #define CLIP_MOUSEDOWN 2 #define CLIP_MOUSEUP 3 //struct SDL_Rect //{ // int x; // int y; // int w; // int h; //}; void set_clips(SDL_Rect * clips); int main(int argc, char **argv) { SDL_Rect clips[4]; set_clips(clips); return 0; } //I get the error in this function on every line void set_clips(SDL_Rect * clips) { //CLIP_MOUSEOVER and the others are defined to 0, 1, 2, and 3 using #define clips[ CLIP_MOUSEOVER ].x = 0; clips[ CLIP_MOUSEOVER ].y = 0; clips[ CLIP_MOUSEOVER ].w = 320; clips[ CLIP_MOUSEOVER ].h = 240; clips[ CLIP_MOUSEOUT ].x = 320; clips[ CLIP_MOUSEOUT ].y = 0; clips[ CLIP_MOUSEOUT ].w = 320; clips[ CLIP_MOUSEOUT ].h = 240; clips[ CLIP_MOUSEDOWN ].x = 0; clips[ CLIP_MOUSEDOWN ].y = 240; clips[ CLIP_MOUSEDOWN ].w = 320; clips[ CLIP_MOUSEDOWN ].h = 240; clips[ CLIP_MOUSEUP ].x = 320; clips[ CLIP_MOUSEUP ].y = 240; clips[ CLIP_MOUSEUP ].w = 320; clips[ CLIP_MOUSEUP ].h = 240; }
That code compiled for me as well, but I'm still having problems. I created a new project and changed the compiler settings a bit to include the SDL library, then put in the code:
#include <SDL/SDL.h>
#define CLIP_MOUSEOUT = 0
#define CLIP_MOUSEOVER = 1
#define CLIP_MOUSEDOWN = 2
#define CLIP_MOUSEUP = 3
void set_clips( SDL_Rect* );
int …
Your code worked for me too, so I replaced the '->' with '.', but was still getting an error. I was messing around with my code for a while, and finally found that replacing the CLIP_MOUSE stuff with actual numbers worked. So, I'm wondering now, why would
clips[ 0 ].x = 240
work, but not
#define NUMBER 0
clips[ NUMBER ].x = 240
I thought #define NUMBER 0 would be the exact same thing as putting in a 0 yourself ?
Also, I should've mentioned this earlier, but SDL_Rect comes from an outside library. The definition is:
typedef struct{
Sint16 x, y;
Uint16 w, h;
} SDL_Rect;
I have a function which takes an array of SDL_Rect (which is a data structure containing four integers, x, y, h and w), and assigns values to the data members. However, when I try to compile, each line generates the error "error C2059: syntax error : '='".
int main()
{
SDL_Rect clips[ 4 ];
set_clips( clips );
}
//I get the error in this function on every line
void set_clips( SDL_Rect *clips )
{
//CLIP_MOUSEOVER and the others are defined to 0, 1, 2, and 3 using #define
clips[ CLIP_MOUSEOVER ]->x = 0;
clips[ CLIP_MOUSEOVER ]->y = 0;
clips[ CLIP_MOUSEOVER ]->w = 320;
clips[ CLIP_MOUSEOVER ]->h = 240;
clips[ CLIP_MOUSEOUT ]->x = 320;
clips[ CLIP_MOUSEOUT ]->y = 0;
clips[ CLIP_MOUSEOUT ]->w = 320;
clips[ CLIP_MOUSEOUT ]->h = 240;
clips[ CLIP_MOUSEDOWN ]->x = 0;
clips[ CLIP_MOUSEDOWN ]->y = 240;
clips[ CLIP_MOUSEDOWN ]->w = 320;
clips[ CLIP_MOUSEDOWN ]->h = 240;
clips[ CLIP_MOUSEUP ]->x = 320;
clips[ CLIP_MOUSEUP ]->y = 240;
clips[ CLIP_MOUSEUP ]->w = 320;
clips[ CLIP_MOUSEUP ]->h = 240;
}
I've been trying to figure it out for hours. Any idea what causes it? (I'm willing to bet it's something really stupid).