How do i Declare methods in public and write the code in private

383 Views Asked by At

I have been given this code with the restraints that i can not edit the public in anyway and am not allowed to call any other library's other than the ones specified.

Class example
{
private:
  vector<int> vector_1;
  void function_1(string name)
  {
  "code for function one goes here"
  }

public:
  void function_1(string name);
};

is there way to map function_1 to a method in private? so that in main: a method call would act like it was it was in public however it is in private (considering the constraints)

-edit: i have read the rules and research a bit however could not find a true answer to what i was looking for. Here is the code sample:

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class MapFunction
{
 private:
 string responce;
 string input;
 vector<int> templist;

public:
 void AskForInput();
 void Output(string input)
 };



int main(void) {
  MapFunction a;
  return 0;
}

The restraints of my solution is that i am not allowed to make changes to the public section of the class or put code into main. Normally i would create the method inside of the class by creating a method like this

#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>

using namespace std;

class MapFunction
{
private:
    string responce;
    string input;
    vector<int> templist;

public:
    void AskForInput(void);
    void Output(void);
};

void MapFunction::AskForInput() {
    cin >> input;
};
void MapFunction::Output() {
    cout << input;
};


int main(void) {
    MapFunction a;
    a.AskForInput();
    a.Output();
    return 0;
}

however i wondering if it was possible to place the methods inside private and allowing main to access them without changing the way it is called in public

1

There are 1 best solutions below

0
On

A member function always has access to all members (private and public ones), no matter if it is private or public itself. So a function cannot behave as "in private" or "in public", it just behaves as "function".

Private/public only is of relevance for accessing the function from outside the class – either one can (public) or cannot (private) (and additionally, there's yet protected, which is like private except for inheriting classes).

Finally: There's yet the friend keyword: By declaring a function (or a class) friend, you give it access to the private members of the class. This access comprises all members, though, you cannot give access just to specific members (at least not without tricks such as proxy classes). Example:

void outerFriend();
void outer();

class C
{
public:
    void publicInner();
private:
    friend void outerFriend();  
    void privateInner();
};

void outer()
{
    C c;
    c.publicInner(); // legal
    c.privateInner(); // not accessible!
}
void outerFriend()
{
    C c;
    c.publicInner(); // legal
    c.privateInner(); // legal(!)
}