Like the title says; Why would you want to make class objects (instances of a class) instead of built in types parameters of a function and in C . E.g. Why do this: class Person { public: void SetAge(Person &Age); instead of this: class Person { public: void SetAge(int iAge);. I don't really understand why don't you create parameters using only built in data types.

Recommended Answers

All 3 Replies

To pass information, and maybe change values in passed parameters where changes are retained outside the current function.

class Address // Assumes address is in USA
{
private:
    std::string street;
    std::string city;
    std::string state;
    std::string zipcode;
public:
    const std::string& getStreet() const;
    const std::string& getCity() const;
    const std::string& getState() const;
    const std::string& getZipCode() const;
};

class Map
{
.
.
.
public:
    void showLocation( const Address& addr ) const;
    // Alternative implementation:
    void showLocation( const std::string& street,
                       const std::string& city,
                       const std::string& state,
                       const std::string& zipcode ) const;
};

So, the class Map can use the getter methods in Address::showLocation( const Address& ) const to determine where the location is, and then display that. Note that this is a VERY rudementary example, but the point is that passing objects instead of lower-level scalar data can be useful, more terse, and less error prone.

commented: Great answer! +15

This maybe can help you:

// classes example
#include <iostream>
using namespace std;

class Rectangle {
    int width, height;
  public:
    void set_values (int,int);
    int area() {return width*height;}
};

void Rectangle::set_values (int x, int y) {
  width = x;
  height = y;
}

int main () {
  Rectangle rect;
  rect.set_values (3,4);
  cout << "area: " << rect.area();
  return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.