0

i am trying to understand how can i access private classes through public classes because some experts said to me that i have to use only private classes. But i can't understand why this doesn't work.I really don't know how can i access private through public its really confusing .

#include <iostream>
#include <string>
using namespace std;

class ManolisClass{

public :
    void setName(string x){
        name = x;
    }

    string getName(){
        return name;
    }

private :
    string name;
};

int main()
{
    ManolisClass bo;
    getline(cin, bo.setName() );
    cout << bo.getName();
    return 0;
}
JBL
  • 12,588
  • 4
  • 53
  • 84
Manuel Pap
  • 1,309
  • 7
  • 23
  • 52
  • Access private classes through public classes? Are you talking about inheritance? I am confused – nikolas Jul 24 '13 at 09:21
  • What exactly is the problem? Does it compile? Does it yield an unexpected result? Please expand your question. – arne Jul 24 '13 at 09:22
  • sorry, i am really sorry...but i am learning this now! they said to me that i have to use ONLY private classes and never public. – Manuel Pap Jul 24 '13 at 09:22
  • When people say to use private data members, they don't mean to expose all of them with setters and getters. That ruins the point of any abstraction your class does. – chris Jul 24 '13 at 09:23
  • Your `getline` call is wrong! You pass it the *result* of the `setName` member function call, but it doesn't return anything. The `setName` function also needs an input argument, which you do not provide. You need to store the input in a temporary variable, and call `setName` with this variable. – Some programmer dude Jul 24 '13 at 09:23
  • Pass the string to setName as const reference to avoid a copy. – Neil Kirk Jul 24 '13 at 09:36

1 Answers1

1

Your access methods are correct, but as you can see from the signature of the function setName, you have to provide a string to set the name of the class. getLine method takes a string as argument. You could create an intermediate variable and use that variable to set the name of the class.

Here is how one can do it.

string temp;
getline(cin, temp);
bo.setName(temp);
mkirci
  • 169
  • 5
  • thanks! thats what i want! thank you so much! some experts said to me that i have to use only private classes because the public classes are bad programming, i am learning now so i have to listen to them ! thank you – Manuel Pap Jul 24 '13 at 09:29