-4

I am very new to object oriented programming in c++ and I am having some difficulty with syntax when access specifiers are used inline with variables, classes, or functions. The code below is not mine. It is from this post. Judging by the popularity of the thread I'm sure others got it to compile. However I am having difficulty.

public class CartEntry
{
    public float Price;
    public int Quantity;
}

public class CartContents
{
    public CartEntry[] items;
}

public class Order
{
    private CartContents cart;
    private float salesTax;

    public Order(CartContents cart, float salesTax)
    {
        this.cart = cart;
        this.salesTax = salesTax;
    }

    public float OrderTotal()
    {
        float cartTotal = 0;
        for (int i = 0; i < cart.items.Length; i++)
        {
            cartTotal += cart.items[i].Price * cart.items[i].Quantity;
        }
        cartTotal += cartTotal*salesTax;
        return cartTotal;
    }
}

I tried a simple class to identify the problem

This compiles:

#include <iostream>
class C{
    int i;
    };
int main(){}

This does not:

#include <iostream>
class C{
    public int i;
    };
int main(){}

nor does this:

#include <iostream>
public class C{
    int i;
    };
int main(){}

This does:

#include <iostream>
class C{
    public: int i;
    };
int main(){}

This does not:

#include <iostream>
public: class C{
    int i;
    };
int main(){}

I am using the GNU c++ compiler V6.3.1 without any build flags. If this syntax is incorrect, why do I see it demonstrated so often. If it is correct, am I missing a compiler option, header file, or something else?

Community
  • 1
  • 1
mreff555
  • 1,049
  • 1
  • 11
  • 21

1 Answers1

2

The answer is simply that your example post discusses Java instead of C++. The syntax for access specifiers and this pointers (as well as many other items) is different.

synchronizer
  • 1,955
  • 1
  • 14
  • 37
  • Interesting. I never tried Java. I never realized how similar the languages looked. Thanks! – mreff555 Jan 15 '17 at 01:13
  • @mreff555 Yes, a lot of the syntax in Java is C-like. I suggest that you do all of the research you can before making a post in the future though. :) – synchronizer Jan 15 '17 at 01:14
  • For the record, the post I was referring to was this one. http://stackoverflow.com/questions/226977/what-is-loose-coupling-please-provide-examples. Not the one referenced by melpomene. Java is not explicitly mentioned in the post or tags and I found the post with the search string "c++ loose coupling". I would agree that it is important to do research before posting. but as a new programmer with no experience in Java I really had no way of knowing. – mreff555 Jan 15 '17 at 01:20