mitrmkar 1,056 Posting Virtuoso

No. The program didn't like that constructor for some reason.
Success!

Wow, this is getting actually quite entertaining :)

Sorry AD, but you made a radical change there. That is, now there is an object instantiated in the usual way, i.e. "WCS m(L"Hello");", i.e the code is pretty much guaranteed to work.

But the original problem arose due to the way the constructor was used and the attempt to reference the (more or less) temporary object.

[EDIT]
@CppBuilder
GCC docs state one aspect with regard to the temporary objects and their lifetime, I think it's quite relevant here, since you mentioned referencing member variables, so maybe check out Temporaries May Vanish Before You Expect.

mitrmkar 1,056 Posting Virtuoso

I did all you said.

I assume you are addressing me, and if so, the code is still somewhat 'off' with regard to what I meant

#include <conio.h>
#include <iostream>
#include <string>

class WCS
{
public:
	wchar_t* p;
	WCS(const std::wstring& wstr)
	{
		wchar_t* c = new wchar_t [wstr.size() + 1];
		wcscpy_s(c,wstr.size() + 1,wstr.c_str());
		p = c;
	}
	~WCS()
	{
		std::cout<< "destructed\n";
		delete [] p;
	}
	operator wchar_t*&()
	{
		return p;
	}
};

int main()
{
  std::wstring wstr(L"hello");
  //// not like this ...
  //// wchar_t* const& c = WCS(wstr);

  // construct the object and get a const reference to it 
  // to keep it around as long as needed here
  WCS const & obj_ref = WCS(wstr);
  std::wcout << obj_ref.p;

  _getch();
}

>> And another thing I should add to the "essential properties" is that a referece to a member is is enough to prevent destruction.
I think that it just does not apply here, you don't have a 'valid' object around in the first place (mm, interesting topic, maybe some draft-standard reading is in order).

>> Does this program have an exception in your computer?!
Yes, that's because the object is destroyed too soon.

mitrmkar 1,056 Posting Virtuoso

no, see this

What's there is not quite same thing that you are doing in this thread (very close though).

However, you are not referencing the object that gets constructed, but rather its member variable. The object really gets destructed before the output.

So, to keep the object around long enough to see the output, it would be:

WCS const & ws = WCS(wstr);
wcout << ws.string;

And there is a little too-small-a-buffer hitch ...

wcscpy_s(c, wstr.size() + 1, wstr.c_str());

[EDIT]
A good string-catch by AD, so the above .string really should be something else that it is. But you get the point I think.

mitrmkar 1,056 Posting Virtuoso

Unless I am misunderstanding, which is completely possible haha

Ancient Dragon didn't say that the keywords are to be hard-coded. So you'll just have to process the command line arguments and gather the keywords for later lookups.

Depending on how many keywords there could be, it might be easier to specify the keywords through a file i.e. these words would also be read in from a file rather than from the command line.

mitrmkar 1,056 Posting Virtuoso

why does this program have an exception in VC++ 2008 Express?
I tested it in a borland compiler & there was no exception.

VC probably destructs the object as soon as the reference has been set i.e. before any output.

Just out of curiosity, when you run the program under borland, does the destructor get called before the "wcout << c"?

mitrmkar 1,056 Posting Virtuoso

I'm sorry, but I don't see this working, mitrmkar.

Hmm, it really should work, that's a method were both of the objects are of same class, hence it does not matter whether or not there is access to a private member variable.

Here is a little test program ...

class access_test
{
private:
  int answer;

public:
  access_test(int i) : answer(i) {}

  int plus(const access_test & other)
  {
    // increment this instance's 'answer' by other's
    answer += other.answer;
    // and return the current value ...
    return answer;
  }
};

#include <iostream>
int main()
{
  access_test fourty(40);
  access_test two(2);

  std::cout << fourty.plus(two) << std::endl;

  std::cin.get();
}

that should output 42 (which is the correct answer)

[EDIT]
Oh, I didn't at first notice what you were saying ...
>> In addition, if data_ were static, the matrices would be stored in the same memory

Yes, that would be quite unsuitable, I sort of tried to point that out there in post #2.

mitrmkar 1,056 Posting Virtuoso

how do I refer to each individual matrix since both are stored in data_?

As per the above class declaration ...

// Add Matrix b to this matrix
void Matrix::Add(Matrix b)
{
    data_[ <index here> ] += b.data_[ <same index here> ];
}

That's how you access the other object's (b) data_ member. So the next step would be to put that inside a loop to process all the data_.

mitrmkar 1,056 Posting Virtuoso

The file that you posted above (that is, your post #1), actually contains both
#include <iostream>
using namespace std;

So given that you are really getting those errors that you posted, now, are you absolutely sure that you are compiling the correct file(s)? I have a hunch that you are compiling the original 10 year old files.

mitrmkar 1,056 Posting Virtuoso

well i do not want to use the system syntax, isn't there any other way to open a program in c++?

No there isn't. You have to resort to OS specific functions to start programs.

mitrmkar 1,056 Posting Virtuoso

Hmm, that certainly will not work. You haven't paid too much attention to the GetProcessTimes() documentation.

Below is code that tries to get the information you are after. If it succeeds, you can incorporate that functionality into your program (e.g. make it a function of its own) . See if it works on your system ...

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
  // get the current process' id, this should pretty 
  // much always succeed ...
  const DWORD PID = GetCurrentProcessId();

  // try to get a handle to this process
  const HANDLE hProcess = OpenProcess(
    PROCESS_QUERY_INFORMATION,
    FALSE,
    PID);

  // was it a success ?
  if(hProcess == NULL)
  {
    // no ...
    cout << "OpenProcess() failed, error: " << GetLastError() << endl;
    return 0;
  }

  FILETIME CreationTime = {0};
  FILETIME ExitTime     = {0};
  FILETIME KernelTime   = {0};
  FILETIME UserTime     = {0};

  // try to get the times
  if(GetProcessTimes(
      hProcess,
      &CreationTime,
      &ExitTime,
      &KernelTime,
      &UserTime
  )){
    // succeeded, the times are now in the respective FILETIMEs
    cout  <<  "GetProcessTimes() succeeded!\n"
              "Todo: figure out the seconds that this process has\n"
              "spent in user and in kernel mode.\n";
  }
  else {
    cout << "GetProcessTimes() failed, error: " 
          << GetLastError() << endl;
  }

  // clean up
  CloseHandle(hProcess);

  return 0;
}

GetProcessTimes() documented -> GetProcessTimes()
OpenProcess() documented -> OpenProcess()

About these FILETIME structures that are used ...

All times are expressed using FILETIME data structures. Such a structure contains two 32-bit values …

mitrmkar 1,056 Posting Virtuoso

i left out initializing total = 0. Why is it important to initialize it to 0 before entering the loop?

Basically, if you don't initialize it, then the initial value may be pretty much anything. The compiler doesn't care, it expects you to do the initialization. Maybe, try it out, put a cout << total << endl; prior to entering the loop and see what the initial value is.

mitrmkar 1,056 Posting Virtuoso

sorry but I really couldn't understand the += operation. Are there any alternate methods?

Well, one way, perhaps more clear to you, would be

float total = 0.0f;
while(looping)
{
  float calculated_value = some_func();
  // add to the 'total' ...
  total = total + calculated_value;
}

So, += is another form of value = value + some_other_value , they both do exactly the same thing;

mitrmkar 1,056 Posting Virtuoso

Perhaps try a simplified version first ...

int main(void)
{
  float total = 0.0f;

  // loop twice ...
  int count = 2;

  while (count --)
  {
    float weight = 0.0f,
          distance = 0.0f,

    cout  << "Item " << count << "Net weight in kg: ";

    cin >> weight;

    cout << "Distance travel in km: ";

    cin >> distance;

    // double the values and sum up ...
    total += 2* weight + 2 * distance;

    cout << "The total cost is now " << total << endl;
  }
  return 0;
}

PS. If you don't have any specific reason to operate with float (such as saving memory), then rather switch to double s altogether.

mitrmkar 1,056 Posting Virtuoso

The error is quite obvious

char *compareFN=NULL;
// 'compareFN' is a null pointer, strcpy() is guaranteed to fail
strcpy(compareFN, ((*myPtr).second)-> getEmpFirstName());

So strcpy() copies the source buffer to the destination buffer, which you don't have. In other words, you must have a char buffer sufficiently large to hold the incoming data + the terminating null character ('\0'). Perhaps see strcpy().

[EDIT]
Beaten by IsharaComix, providing a good suggestion, though I still suggest that you check out the strcpy().

mitrmkar 1,056 Posting Virtuoso

It appears as if

total += weightcount(weight) + distancecount(distance);

would do it. And also initialize total to zero before entering the loop.

mitrmkar 1,056 Posting Virtuoso
int main()
{
    Matrix A(2, 3);
    Matrix B(3);

    return 0;
}

>> Then does this create 2 separate matrices stored in data_?
Yes it does. You have two distinct objects of type Matrix, they both withhold their own vector, so there is no interference between the two objects.

If you'd have a static vector there, then each instance of a Matrix would operate on the very same vector, so

class Matrix {
 public:
 <snip>

 private:
  static std::vector<double> data_; // Vector storing the matrix data
};

Then you'd be better of passing in the Matrix objects by reference and even by const reference, just to avoid temporary Matrix from being created upon method calls, so rather

// if 'b' is not supposed to change -> make it const
// and pass it in by reference, to be more efficient
void Subtract(const Matrix & b);
mitrmkar 1,056 Posting Virtuoso

Are you sure you posted a relevant code snippet? The error message says:

error: no matching function for call to ‘merge(vertex*&, int&, int&, int&)

So there should be a call to merge(...) , but there isn't.

mitrmkar 1,056 Posting Virtuoso

Yes, it's been suggested.

I know, it's just that the exact/real reason why that line is wrong hasn't been pointed out. Hence my two cents.

mitrmkar 1,056 Posting Virtuoso
Area::Area( int y, int x )
{
    for ( int i = 0; i != y*x; ++i )
    {
        // the compiler sees the below line as a function declaration,
        // 't' is a function that takes no arguments and returns a Tile.
        Tile t();

        area_tiles.push_back(t);
    }
}

So, the fix is to remove the parenthesis i.e.

Tile t;
mitrmkar 1,056 Posting Virtuoso

would it affect the program any?

Could you provide an example or two regarding the changes you mean?

mitrmkar 1,056 Posting Virtuoso
// First you have to do this
for(for_loop_conditions)
{
   free(charArray[i]);
}

// ... and then also this
free(charArray);

So there has to be a matching free() for each malloc() that you do.

PS. Just to be clear ... if charArray is also dynamically allocated, it needs to be declared as: char ** charArray i.e. not char *charArray .

mitrmkar 1,056 Posting Virtuoso

I sort of understand what your saying, that the function doesnt care what it is....just where the data starts and ends.

A function does not know where the data ends unless you tell it to the function. So if you pass an array into a function, be sure that the function also gets the information about the array's size (number of elements in it, that is).

mitrmkar 1,056 Posting Virtuoso

Adding a note ... you are doing some out-of-bounds access there, for example

// two 'coord' objects, meaning
// that you only can access indexes 0 and 1, nothing else.
coord asteroid[2];
...
//Collision check
for(int i = 0; i< 2; i++)
{
  asteroid[i].collision(asteroid[i+1]);
}
mitrmkar 1,056 Posting Virtuoso

<nevermind>

mitrmkar 1,056 Posting Virtuoso

I have done the same in Java

http://www.technicalypto.com/2010/02/stack-using-linked-lists-in-java.html

Good for you, but please don't resurrect an old C++ thread just for the sake of saying that you've done something similar in Java, thank you.

mitrmkar 1,056 Posting Virtuoso

I have one warning at line 77 that says temp is not initialized. Please show me where to fix this.

About swapping, you need to have a buffer for swapping the strings. A mere char * used as you intended is not enough (it would cause havoc if used). So, at the very least, change to

/*Swapping*/
  /* 'temp' - a buffer for swapping the strings */
  char temp[12];
  strcpy_s(temp,12,array[j]);
  strcpy_s(array[j],12,array[j+1]);
  strcpy_s(array[j+1],12,temp);

You might use a #define to define the sizes of the char arrays, so that it would be consistent throughout the code. As of now there are buffers of sizes 10, 12, 20.

So maybe

#define STRING_BUFFER_SIZE 20
int main()
{
    char input[STRING_BUFFER_SIZE], output[STRING_BUFFER_SIZE];
    /* ... and so on */
mitrmkar 1,056 Posting Virtuoso

Actually, for all the *_s functions -- stop using them.

I would rephrase that a little

Actually, for all the *_s functions -- stop using them if you aim to write standards-compliant code. Otherwise, learn and use them (these functions exist for a good reason). Just be aware that these functions are available only with recent Microsoft's compilers.

mitrmkar 1,056 Posting Virtuoso

//Here is the function of inserting nodes.I tried using strcmp but its still not working.

What do you mean by "still not working"?

Do you really want to use exit() there? I.e. your program gets terminated when duplicate data is encountered.

A suggestion regarding initialization of a tree_node

struct tree_node
{
  // default constructor
  tree_node() 
  : left(NULL), right(NULL)
  {
    // pointers are now initialized to NULL
  }
};

// So that would make somewhat cleaner code ..
tree_node* t = new tree_node;
// t->left and t->right are now automatically NULL
...

Then you might expand that even little more and also pass the data through the constructor.

mitrmkar 1,056 Posting Virtuoso

When you compile on Windows, don't include the following headers:
<sys/time.h> and <sys/resource.h> but <windows.h> instead.

Then ...

  • use GetProcessTimes() instead of getrusage()
  • add necessary C++ headers, such as <iostream>, also <cassert>
  • handle "redefinition of default parameter" errors (i.e. delete default parameters from the function/method definitions
  • handle warnings such as 'possible loss of data' and 'truncation of data' etc ...
mitrmkar 1,056 Posting Virtuoso

I think you are just 'moving too fast'. Study the documentation, for example fopen_s().

mitrmkar 1,056 Posting Virtuoso

It seems that the code uses getrusage() , which is not available on Windows. You can use GetProcessTimes() on Windows.

actually it compiles if i change a few things but there are many linker errors. Could someonline please tell me where the problem is at

You could have been more specific about the errors/warnings that you are receiving.

mitrmkar 1,056 Posting Virtuoso

or u can change to..

alfadia.push_back(*alfadi);

Yes, that will push a copy-constructed object onto the vector, however, the object pointed by alfadi has to be deleted to avoid leaking memory.

mitrmkar 1,056 Posting Virtuoso

can u give me the codes... :(

This assignment has been discussed before

Salem commented: OMG, it's contagious! +19
mitrmkar 1,056 Posting Virtuoso

>> But i get error on push_back() while compiling.

The alfadia vector stores objects of type alfa , not pointers to such objects. Then again new alfa returns a pointer to the allocated alfa object.

So, if you want to store objects ...

// vector for storing objects ...
vector<alfa> alfadia;
for(int i=0;i<no;i++)
{
  // 'obj' below, is constructed via default ctor
  alfa obj;
  alfadia.push_back(obj);
}

And if you want to store pointers to objects ...

// vector for storing pointers ...
vector<alfa * > alfadia;
for(int i=0;i<no;i++)
{
  // allocate one alfa object constructed via default ctor
  alfa * obj_pointer = new alfa;
  alfadia.push_back(obj_pointer);
}
mitrmkar 1,056 Posting Virtuoso

Something that looks suspicious ...

TitleState::~TitleState()
{
    isCurrentState=false;
    StartButton.OnCleanup();
    SDL_FreeSurface(background);
}
//------------------------------------------------------------------------------
void TitleState::OnExit()
{
     StartButton.OnCleanup();
     isCurrentState=false;
     SDL_FreeSurface(background);
}

I'd say that be sure that you don't free anything twice i.e. don't do SDL_FreeSurface(background) , if the 'background' has already been freed.

Then change

void Out(char* words)
{
     printf(words);
}

to

void Out(char* words)
{
     printf("%s", words);
}

Remember that printf() treats its first argument as a format string. And if that string happens to 'resemble' a format string, printf() expects one or more arguments (which are not present), so you'd likely be heading for a nasty surprise.

mitrmkar 1,056 Posting Virtuoso

Return a reference to the stream object, that's the way it has been designed to be done (the compiler complains about the streams copy constructor), so

ostream & operator<<(ostream &out, LinkedList list) {
	list.display(out); 
	return out;

Then furthermore, basically you want to pass class/struct objects by reference (or even by const reference) to avoid temporary objects being created upon function calls, so maybe change to

ostream & operator<<(ostream &out, LinkedList & list) {
	list.display(out); 
	return out;
mitrmkar 1,056 Posting Virtuoso

You probably want to start a new VS project that aims to build a library and add your work this far to that project.

The very basic (simplified) scenario goes something like this ...

The output of the project will be a library file (.lib) and optionally a dynamic link library (.dll). When you have your library built, you supply a header .h file, the .lib file, and if you built a .dll, then the .dll too, to anyone who uses the library. (If you don't build a .dll, then the code actually is in the .lib file, in which case it's called a static library).

The header file exposes your library's interface, keeping the end-user's compiler happy (and the end-user too).

The .lib file is needed in order for the end-user to be able to link with your library. And if you built a .dll, then the .dll, containing the actual code, must be available for the end-user at run-time.

Microsoft provides some terse documentation, just detailing out the steps needed for building libraries -> Creating Reusable Code (C++)

Perhaps just go through the steps described there, building a couple of libraries as you go.

mitrmkar 1,056 Posting Virtuoso

how do you create one ?

Im trying to sort objects by their z

You might have something as simple as

// Compares two game objects by 'z'
bool game_obj_compare(const game_obj * lhs, const game_obj * rhs)
{
  return lhs->z < rhs->z;
}

// To sort a vector of game_obj pointers ...
std::sort(v.begin(), v.end(), game_obj_compare);

Since the vector stores pointers, you cannot use the

std::sort(v.begin(), v.end());

version, which uses the overloaded operator < .

mitrmkar 1,056 Posting Virtuoso

what is this (_CreateProcess) in the code??? is this a cast types?

Yes it is a type cast. Why would you want be doing that kind of thing?
You can simply call CreateProcess(...) with the arguments it takes, without hassling with function pointers at all.

mitrmkar 1,056 Posting Virtuoso

Something is wrong with "dear_son"

Yes, you do have room there for 5 children

dear_son = gcnew array<my_child^>(5);

but they need also be given birth first, so

F.dear_son[0] = gcnew my_child;
F.dear_son[0]->mas_1D[1] = 23;

So there were no objects yet, only handles to such, hence
>> not set to an instance of an object

mitrmkar 1,056 Posting Virtuoso

Post solved, thanks much guys :).

Once you've fixed what's mentioned above, test the program by trying to place your ship at 'A0' for example.

mitrmkar 1,056 Posting Virtuoso

>> except sometimes it does choose the same spot twice, any tips on how to prevent that?

Have a loop in which the computer chooses, so if the location is already used, keep looping until a proper one is found.

Note that the indexes generated by rand() must be within 0..7, inclusive, otherwise you are in trouble.

mitrmkar 1,056 Posting Virtuoso

Sorry but the code you've posted is somewhat vague/insufficient.

By looking at it, even the

>> povbGarniture -> bInserer ((char) szTampon [n]);

should fail. Are you sure that you posted portion of the header file that you are actually using (note that the class declaration is missing the ending brace)?

[EDIT]
Perhaps compile the code with another compiler, if you have one handy.

mitrmkar 1,056 Posting Virtuoso

I think that there is no protection against adding a ship several times to same location (neither for the user nor the computer).

Then are you sure that you have gotten the usage of rand() right, i.e. what does (rand()%8)-1; do?

Then try to type in some unexpected input and watch out for convert() .

PS. Kudos for great formatting.

mitrmkar 1,056 Posting Virtuoso

A remote possibility ... maybe fclose() fails?

mitrmkar 1,056 Posting Virtuoso

A simple suggestion, perhaps try to see what ferror() says?

mitrmkar 1,056 Posting Virtuoso

The <string> header provides a global getline() that does what you need i.e. it works with std::string .
For example

#include <string>
#include <fstream>
#include <iostream>
int main()
{
  std::ifstream ifs("file.txt");
  std::string s;

  while(getline(ifs, s))
  {
    std::cout << s << std::endl;
  }

  return 0;
}
mitrmkar 1,056 Posting Virtuoso

How will I be able to do entities like that if I have to put that inside a function?

That's a difficult one to answer because there is a apparently a lot involved and not knowing the rest of code you already have.

But how about if you step back for a little while and start a new small project that involves a simple object hierarchy (say Base, Entity, TestEntity) and some global object storage.

- The global object storage would maintain/keep track of the objects of these classes (using e.g. vector<Base *> as you already seem to have).
- All of the objects would be allocated dynamically (that is, using new )
- Upon allocation of an object, a pointer to it would be stored in the global storage
- All of the objects would be deleted/destructed (using delete )
- Upon deletion of an object, the pointer to it in the global storage would be removed

I think that might be quite useful in realizing how to design this very basic object management scenario and have it work reliably. Because now it seems, that you are running into trouble because you don't yet know how to do that.

PS. In the previous post I commented that

CTestEntity eRegEntity; // this line is OK

However, that's actually not OK, if you store a pointer to it via the constructor and later on try to delete the object via the pointer. …

mitrmkar 1,056 Posting Virtuoso

Well, I fixed it. I did it by making the variables inside gpGlobalFunctions.Spawn( ) pointers, and initializing them with new.

That sounds good i.e. you are not anymore storing pointers to stack-based objects in the vector. Actually you are allocating those objects with new .

Then regarding the errors ...
test.cpp ...

<snip>

CTestEntity::CTestEntity( )
{
    // force the value to float (otherwise it would be double)
    SetNextThink( gpGlobals.curtime + 1.0f);
}

<snip>

CTestEntity eRegEntity; // this line is OK
// But the following must be moved inside a function
gpGlobalFunctions.RegisterEntity( eRegEntity );

The header files you posted seem to be OK in terms of having #include guards, so the compiler probably got mixed up because of that outside-function usage of gpGlobalFunctions.RegisterEntity(...) you have there. So make the changes, re-compile and see what you get.

One thing for you to notice, you seem to be using constructs as

void some_func(char * p1)
{
    if(p1 == "debug_entity_test")
    {
        // something here
    }
    else if(p1 == "debug_entity_test_other")
    {
        // something here too
    }
}

That may work for you as intended and probably has been doing so, but when you compare C-style strings, use strcmp() for figuring out whether two strings match or not, so

void some_func(char * p1)
{
    if(0 == strcmp(p1, "debug_entity_test"))
    {
        // p1 equals "debug_entity_test"
    }
}

There are other strcmp() -family functions also, maybe look them up.

mitrmkar 1,056 Posting Virtuoso

>> Is it possible that calling the non-virtual method on the object of subclass is sometimes done via one definition and sometimes via the other?
As far as I understand the question, I would say no.

>> The method in the superclass was empty, didn't even return anything.
That's bad, when a method signature says it returns something, you must make it return something (that matches the signature).

By the way, here are more options GCC options Options Controlling C++ Dialect

And if you browse the GCC online docs site, you'll find even more. So, try figuring out what good they do and use them as you see fit making good use of the compiler. And make sure you are looking at the documentation that matches your compiler version.