Hunter K. Hunter K. - 1 year ago 41
C++ Question

Classes - Attempting to access private variable from public function leads to error

I've recently learned about classes (and defining function prototypes in header files) and what not. I was testing this today and ran into an error:
I believe it has to do with a function inside the public portion of a class, not being able to access a variable in the private portion of the same class.

What I'm trying to do: I want print() to be able to print out the value of test. (Located in Main.h / Main.cpp).

I have 4 files, Main.cpp, Main.h, Source.cpp, Source.h. Both are really short:

// Main.h (The header file to Main.cpp)

#pragma once

#include <iostream>
#include <Windows.h>

using namespace std;

class Test {
DWORD test = 0;

void print();

// Main.cpp (The file that defines the functions)

#include "Main.h"

void Test::print() {
cout << "function called" << endl; // this prints out
cout << "value of test: " << test << endl; // but this doesnt, so I'm pretty sure it has something to do with Test::print() not being able to read test.

// Source.h (The header file to Source.cpp)

#pragma once

#include "Main.h"

extern Test *test;

// Source.cpp (The file that contains the class)

#include "Source.h"
#include <Windows.h>

Test *test;

void main() {
test->print(); // "test was nullptr" error points here

What I know is happening: The function print() is successfully being called by main. However I get the following error:

Exception thrown: read access violation
test was nullptr

Pretty sure the "read access violation" error is coming from Main.cpp.

Any help?

Answer Source
  1. Dump source.h - You do not need it
  2. Source.cpp You are using a pointer that has not been allocated

Make life easier - change Source.cpp to

  #include "Main.h"  
  int main() {
      Test test;

      return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download