3

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!

  • 1
    you're pretty close actually, `void printclass::print()` -> `void printclass::print( const char* array )` & `void print( const char* array );`. – George Jul 07 '17 at 10:27
  • 3
    Perhaps you should [find a good beginners book or two to read](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)? – Some programmer dude Jul 07 '17 at 10:28
  • Wot no *constructor*? Eventually you could show off and build an *overload* for `>>` for your type. Then you could use `cin` *directly* for your type. – Bathsheba Jul 07 '17 at 10:28
  • 1
    @Bathsheba Knowing that OP does not understand the basics of OOP, I think that overloading operators is out of the scope of the question. – Garmekain Jul 07 '17 at 10:48
  • Upvoted because of showing us your detailed point of view of the problem and really trying to understand concepts. – Garmekain Jul 07 '17 at 10:51

1 Answers1

1

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.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135