-3

Coming from Java, I'm quite accustomed to being able to include Classes that I've made within other classes eg:

class Pepperoni{

}

class Pizza{
  Pepperoni pepperoni;
  Cheese cheese;
}

However in C++, it seems to interpret what I see as declarations, as instead: function calls to initialise a 'Pepperoni' class using the default constructor with empty parameters.

What I'm wanting to do is to be able to create a Pizza class and initialise the 'Pepperoni' and 'Cheese' member variables taken from input on it's constructor. ie something like:

Pizza::Pizza(Pepperoni pepperoni, Cheese cheese){
  this.pepperoni = pepperoni;
  this.cheese = cheese;
}

Is this just wishful thinking? Do I have to do it another way? Have I overlooked wonderful feature of C++?

Thanks!

Liang
  • 383
  • 4
  • 13
  • What's your actual problem? Did you just try it? Should work fine. – πάντα ῥεῖ Aug 21 '15 at 14:09
  • I love pizza man, gonna order one right now –  Aug 21 '15 at 14:11
  • 2
    `this` is a pointer to the object in C++, so use `this->cheese = cheese;` or use another name for the input: `cheese = newCheese;` – stefaanv Aug 21 '15 at 14:16
  • The -> notation seems to have done the trick. I think I'll need to do some more testing. Thanks @stefaanv – Liang Aug 21 '15 at 14:20
  • @πάνταῥεῖ I was having an issue where I had actually declared a parameter input for the Pepperoni constructor, however the compiler seems to have assumed that for some reason I was calling the constructor without parameters, when in actual fact all I wanted to do was to declare the Member variable – Liang Aug 21 '15 at 14:22
  • @Liang: Java and C++ behave really different for this. You better read a book about this or at least: http://www.cprogramming.com/java/c-and-c++-for-java-programmers.html – stefaanv Aug 21 '15 at 14:29
  • I do know about the differences between Java and C++. The problem was that there seemed to be a pretty huge inconsistency in C++ in how it handles the declaration of primitive types versus non-primitives like in the example I mentioned. Had I substituted 'int' for pepperoni and 'float' for cheese, the examples would work absolutely without issue... and that really bugs me – Liang Aug 21 '15 at 14:35

1 Answers1

0

This works different in Java and C++. While in Java all you have are references to heap-based objects, in C++ what you have written is OBJECT itself, not reference to it. I suggest you to read some materials on C++ OOP basics to better understand that. For example, you can read this and follow links to other questions included in this question: C++ Pointer Objects vs. Non Pointer Objects

Community
  • 1
  • 1
ivan.ukr
  • 2,853
  • 1
  • 23
  • 41