-1

I've got this class called Heap. I'm trying to have an instance of Heap as a private member in a class called Graph but that doesn't seem to work.

class Heap{
  private:
    Node* container;
    int size; 
    //... some more attrs ...
  public: 
    Heap(int inSize){
      size = inSize
      //... initialize other private attrs ...
    }

class Graph {
   private: 
     int size; 
     Heap h(90); 
   public: 
     Graph(int inSize){
       size = inSize;
     }

After looking at this post, How to create an object inside another class with a constructor?, I still can't figure out why I am not allow to initialize Heap within the class Graph. My guess is that private members can't be initialized, they're just placeholders so no physical memory is given to them. One of the comments in this post states that having a pointer is not a good practice.

So my questions are: 1. why isn't this a good practice? if it indeed isn't a good practice. 2. why can't I instantiate another class object from within another class's private attributes. 3. is there another way besides a pointer to solve this problem? 4. Also, it seems that if I don't have a custom ctor, and just use a default one, it works, again, I have no idea why.

3
  • Use member initializer lists in your constructor. Commented Nov 20, 2015 at 22:45
  • can you elaborate as to why this will not work? Commented Nov 20, 2015 at 22:46
  • Because Heap h(90); is simply wrong syntax. Commented Nov 20, 2015 at 22:47

1 Answer 1

0

I'm trying to have an instance of Heap as a private member in a class called Graph but that doesn't seem to work

You are using the wrong syntax.

Heap h(90);

is not a valid syntax. Use:

Heap h;

Initialize it the constructor using

 Graph(int inSize) : size(inSize), h(90) { } // Or the appropriate size.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.