Cherrypowder
Cherrypowder

Reputation: 57

How do I print a variable from main with a function in a class, Help understanding OOP c++

Section 9(1/4) out of 11 of my c++ introduction webclass;

I have no idea what I'm doing. I'm unsure even of what terms to search for(first touch with OOP).

- I need to print the cin in main with a function in a class, So far I have come up with a class with a string variable and a function that do nothing;

#include <iostream>
#include <string>
using namespace std;
        class printclass 
    {
        public:        
        string array;
        void print(); 
    };

    void printclass::print()
    {
        cout << array;
    }

Main program(cannot be edited);

   int main()
{
  char array[50];

  cout << "Enter string:";
  cin.get(array, 50);

  printclass printer;
  printer.print(array);
}

It is my understanding that the printclass printer; creates an object 'printer' with the printclass class and thus knows how to use the functions in the class on sort-of a blank page that is declared with the call, am I far off?

How do I print the value of the array in main with the function?

The exercise has been translated from finnish, please excuse blunt grammar and user stupidity. Thank you for your time!

Upvotes: 3

Views: 66

Answers (1)

Bartek Banachewicz
Bartek Banachewicz

Reputation: 39370

am I far off?

Kinda. You've incorrectly assumed the interface of your printclass. Here's a correct one1 from the example posted:

class printclass {
public:
    printclass();
    void print(const char* str);
};

From that it's quite easy to spot your mistake; you've assumed that your class has to store the array to print, while the interface passes it directly. It's enough to implement the print in terms of str without any member variables:

void printclass::print(const char* str) { // could be const
    std::cout << str;
}

Note: the constructor can of course be left alone and it will default to what you want.


1One of many possible interfaces, but I've picked the most likely.

Upvotes: 1

Related Questions