-5

I need some clarification about this issue. I have a class called con.

class con
{
 public:
 con();
 int readIndex;
}

in con.cpp:

con::con()
{
readIndex = 0;
}

in main:

con = new con();

now readIndex is not 0 as I wanted. Watch window shows that the value is 0xcdcdcdcd {???} and the type is now int* and not int which means that a variable will become a pointer if it's class object is created using new? I then tried to change the code to *readIndex = 0; but I got a write access violation. So how should I set the value of readIndex to 0 after all? `

David912
  • 378
  • 1
  • 2
  • 11
  • 1
    `0xcdcdcdcd` = uninitialized heap memory. https://stackoverflow.com/a/127404/487892 Your code for con::con() must not be what you typed. – drescherjm Oct 02 '17 at 21:31
  • 2
    Post an example that demonstrates the problem instead of describing code that we can't see. – interjay Oct 02 '17 at 21:33
  • Please make a [mcve]. Also you may want to read a [book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – nwp Oct 02 '17 at 21:33
  • 1
    ***Your code for con::con() must not be what you typed.*** Or perhaps you are looking at the variable too soon (before it was initialized in the constructor) https://stackoverflow.com/questions/926752/why-should-i-prefer-to-use-member-initialization-list – drescherjm Oct 02 '17 at 21:36
  • @drescherjm you are right I looked too soon. after initialization I got 0x00000000 {???} as readIndex value but of course that's not what I need. What is the right syntax to set the value as 0? – David912 Oct 02 '17 at 21:49
  • 1
    `con::con() : readIndex {} { // c++ statements for the constructor}` – drescherjm Oct 02 '17 at 21:50
  • 1
    `con = new con();` doesn't compile. Post real code. – Pete Becker Oct 02 '17 at 21:58
  • @Pete it does compile. I forgot to add that I declared it as con* con; – David912 Oct 02 '17 at 22:05
  • 1
    I would avoid naming a variable the same as the class. – drescherjm Oct 02 '17 at 22:51

1 Answers1

0

It should definitely initialize readIndex to 0. Just put one print statement and check whether your constructor called properly or not.

Also try with

con::con():readIndex(0) { }

Abhijit Pritam Dutta
  • 5,521
  • 2
  • 11
  • 17
  • I tried that but still no progress. My confusion here is why readIndex is treated by visual studio as a pointer. – David912 Oct 02 '17 at 22:17
  • Are you checking the value by using break point? you are probably checking the value before it initialize. It must initialize the value with 0. No compiler should treat readIndex as a pointer. Something wrong in your debugging. Just declare con *c = new con(); before your statement and check. – Abhijit Pritam Dutta Oct 02 '17 at 22:24
  • Success. changing con = new con(); to con *con = new con(); solved the problem. Many thanks Abhijit – David912 Oct 02 '17 at 22:31