user2804171
user2804171

Reputation: 27

Initializing a pointer in another class

I have a very simple problem. I am trying to learn C++ and I'm having a little problem. Here's the code

system.h

#include <iostream>
#include "processor.h"
using namespace std;

class sys
{
    public:
        int id;
        sys()
        {
            id=0;
        }
};

processor.h

#include <iostream>
using namespace std;
class proc
{
    public:
    const sys* s1;
    s1=new sys();
};  

The error says

"error C2512: 'sys' : no appropriate default constructor available" 

There is a default constructor.

I am a beginner at C++ so please explain what I am doing wrong. Thank You.

Upvotes: 0

Views: 272

Answers (2)

6502
6502

Reputation: 114491

Since class proc is using class sys the include order should be the opposite:

// sys.h
class sys {
   ...
};

// process.h
#include "sys.h"

class proc {
   ...
};

Upvotes: 0

Alok Save
Alok Save

Reputation: 206546

  • You do not initialize class members inside the class body, You do so in the class constructor.
  • const members are special members and they must be initialized in the Member initialization list.
  • Avoid using dynamically allocated memory as much as possible and if you must use smart pointers instead of raw pointers.

proc() : s1(new sys())
{
}

Upvotes: 2

Related Questions