-3

I'm trying to convert a Java program to C++. This is the Java code (which IS working perfectly):

//class MyProgram:

public class MyProgram {
    private static ArrayList mylist;
    //no constructor
    public static int numberOfItems(){
        return mylist.size();
    }
}

//second Java program, MyList

public class MyList {
    public MyList(){
        for (int i = 0; i < MyProgram.numberOfItems; i++)
            System.out.println("Test");
    }
}

This works exactly as I'd hope. However, when converting to C++, the for loop header is giving me errors because it doesn't recognize numberOfItems. The implementation is exactly the same, except a vector instead of an arraylist. My question is: why does not NOT work in C++? Why DOES it work in Java? I've never written an object before where I didn't have to call the constructor to use the methods of that class. How can I achieve this same thing in c++? I can post the c++ code but it looks extremely similar and it seems pointless.


EDIT: C++ CODE:

//MyProgram.h

#ifndef MYPROGRAM_H_
#define MYPROGRAM_H_

 #include <vector>

namespace std;

class MyProgram {
public:

    int numberOfItems();

private:
    vector<Checkpoint> mylist;


};

#endif /* MYPROGRAM_H_ */

//MyProgram.cpp

#include "MyProgram.h"

int MyProgram::numberOfItems()
{
    return mylist.size();
}

//MyList.h:

#ifndef MYLIST_H_
#define MYLIST_H_

#include <vector>

using namespace std;

class MyList {
public:
    MyList();
    virtual ~MyList();
private:
    vector<Checkpoint> path;

};

#endif /* MYLIST_H_ */


//mylist.cpp

#include "MyList.h"

MyList::MyList()
{
    int i;
    for(i = 0; i < MyProgram.numberOfItems(); i++)
    {
        path.push_back(0);
    }
}
user2130057
  • 406
  • 2
  • 5
  • 22

2 Answers2

4

change MyProgram.numberOfItems to MyProgram::numberOfItems()

franji1
  • 3,088
  • 2
  • 23
  • 43
  • 2
    And you should put () – amchacon Feb 27 '15 at 22:43
  • Thank you! This is exactly what I am looking for. Question though, it didn't work with (), only when I removed that did it work. That being the case, what would I do if the method I wanted to call had parameters? In this case it was void so all was well. – user2130057 Feb 27 '15 at 23:18
1

So, you have a misunderstanding of is a class member vs object member. This post will provide you the information that you really need: When do I use a dot, arrow, or double colon to refer to members of a class in C++?.

Also, like frinji1 said, MyProgram::numberOfItems() is what you want.

Community
  • 1
  • 1
v4n3ck
  • 51
  • 3