3 Replies - 500 Views - Last Post: 12 February 2016 - 08:11 AM Rate Topic: -----

#1 O'Niel   User is offline

  • D.I.C Regular

Reputation: 14
  • View blog
  • Posts: 423
  • Joined: 13-September 15

OOP in C++

Posted 11 February 2016 - 04:02 PM

Hello

I've written a small example code to make use of objects and OOP in C++. I think I got the purpose of OOP, but yet I have some questions about it.

Code:
#include <iostream>

using namespace std;

/*Classes*/
//Class for holding GENERAL shapes (Base class)
class Shape {
    //Accessors & mutators
    public:
        //Mutators
        void setWidth(int width);
		void setHeight(int height);
        //Accessors (Must always have a datatype by definition)
        int getWidth();
        int setHeight();
    
    //Here we keep the backing-fields (How do we call them in C++?)
    protected:
        int _width, _height;

};

//Class for SPECIFIC shape :-symbol extends/inherits from Shape (Derived class)
class Square : public Shape {
	public:
		//Method/function returning size (not equal to an accessor)
		int getSize() {
			//We can access width & height cuz it's protected and not private (subclass)
			return _width * _height;
		}

		//Constructor declaring
		Square();
};
class Triangle : public Shape {
	public:
		int getSize() {
			return (_width * _height) / 2;
		}

		Triangle();
};

//Constructors (putting them outside class)
Square::Square() {
    cout << "Square created..." << endl;

    //Setting default width and height for if code wouldn't not
    _width = 5;
    _height = 5;
}
Triangle::Triangle() {
    cout << "Triangle created..." << endl;

    //Setting default width and height for if code wouldn't not
    _width = 5;
    _height = 5;
}

//Functions/methods from classes
void Shape::setWidth(int width) {
	_width = width;
}
void Shape::setHeight(int height) {
	_height = height;
}
int Shape::getWidth() {
	return _width;
}
int Shape::setHeight() {
	return _height;
}

int main() {
    Square square1, square2;
    Triangle triangle1;

    //Setting values for square1
    square1.setWidth(10);
    square1.setHeight(10);

    //Not setting values for square2 (constructor)
    //Getting size of squares

    cout << "\nArea square1: ";
    cout << square1.getSize();
    
    cout << "\nArea square2: ";
    cout << square2.getSize();

    //Triangles
    triangle1.setWidth(5);
    triangle1.setHeight(7);

    int size = (triangle1.getWidth() * triangle1.getSize()) / 2;

	cout << "\n\nArea of triangle: " << endl;
    cout << "\n-> ";
    cout << "(base * height) / 2";
    cout << "\n-> ";
    cout << triangle1.getWidth() << " * " << triangle1.getSize() << " / 2";
    cout << "\n-> ";
    cout << size << endl;

	cin.ignore().get();
	return 0;
}



1) First of all, do I have the terms (Accessor, mutator, base-class,...) in the comments right?
2) How do you call those often protected variables in the class to set and return the actual values? In C# they call it backing-fields, how do they call it in C++?
3) Is my style right? e.g: In C++ you have to put your methods outside your class, do you place them directly under the class, or do you first declare and define all the classes?
class A {};
a();
Class B {};
b();


vs
class A{};
class B{};
a();
b();



4) In C++ mutators set values using a method with a parameter. Is it also possible doing it as a property?
e.g: Foo.bar = gux; instead of Foo.bar(gux);.

5) Constructors are special methods having the same name as the class. These methods are executed each time we create a new instance/object of that class. This way we can set default values.
Or we could set parameters in the constructor so we can define the 'properties' at one line.
Car BMW = new Car(int maxSpeed, string color);

instead of:
Car BMW = new Car();
BMW.maxSpeed(250);
BMW.color("white");


6) Do derive a class from a base class in C++ we use ':', in Java we use 'extends'. We need to define the access-level to say how accessible the objects/methods of the base-class are for THAT derived class.

7) :: is used to set the scope of the defined method.
8) Why do we need to place methods of a class, outside the class using ::?

These are the questions I have for now.

Thanks!

Is This A Good Question/Topic? 0
  • +

Replies To: OOP in C++

#2 jimblumberg   User is offline

  • member icon

Reputation: 5570
  • View blog
  • Posts: 17,217
  • Joined: 25-December 09

Re: OOP in C++

Posted 11 February 2016 - 09:20 PM

Quote

In C++ you have to put your methods outside your class,

No you don't have to put your methods outside your class, but it is quite common to define the class and implement the member functions outside the class definition.

Quote

do you place them directly under the class

With non-template type classes it is normal to place the member function implementations in a separate source file that then #includes the header file.

Quote

or do you first declare and define all the classes?

Each class would normally have a header file that contains the class definition and a implementation source file.

In C++ mutators set values using a method with a parameter. 

In C++ class member functions that "set" a variable to a value is usually called a setter. A member function that retrieves a value is usually called a getter.

Quote

Is it also possible doing it as a property?
e.g: Foo.bar = gux; instead of Foo.bar(gux);.

In C++ there is a difference between a member variable and a member function. And you can't have a member function with the same name as a member variable. Also remember that you can not access a private or protected variable or method outside of the class.

Quote

Constructors are special methods having the same name as the class.

Yes constructors are special member functions that have the same name as the class and have no return type.

Quote

These methods are executed each time we create a new instance/object of that class.

You can have multiple constructors that differ in the type and number of parameters.

Quote

Or we could set parameters in the constructor so we can define the 'properties' at one line.

It is possible to have a class that has no member functions that set values, all the values are set via the constructors.

Next this snippet:
Car BMW = new Car(int maxSpeed, string color);


In C++ normal non-dynamic methods don't need to use new. Your snippet would not compile because you need a pointer to use new.

Quote

:: is used to set the scope of the defined method.


The "::" is called the scope resolution operator. It is used for several purposes, for class resolution, for namespace resolution, and to distinguish between variables with the same name in different scopes, you would use the scope resolution operator to be able to use the more global variable.

Quote

Why do we need to place methods of a class, outside the class using ::?

Because multiple classes can have the same member function and member variable names. Using the class name with the scope resolution operator tells the compiler that the function belongs to a class.

Let's look at the following constructor:
Square::Square() {
    cout << "Square created..." << endl;

    //Setting default width and height for if code wouldn't not
    _width = 5;
    _height = 5;
}


It is considered a better practice to use constructor initialization lists when constructing your classes.

Square::Square() : _width(5), _height(5) {
    cout << "Square created..." << endl;

}


Also note I recommend against using a leading underscore for variable or function names. In many scopes variables starting with a leading underscore are reserved for implementation (compiler) use.


Jim
Was This Post Helpful? 2
  • +
  • -

#3 O'Niel   User is offline

  • D.I.C Regular

Reputation: 14
  • View blog
  • Posts: 423
  • Joined: 13-September 15

Re: OOP in C++

Posted 12 February 2016 - 06:56 AM

Thanks a lot for your answer!
So, about that property-thing (member variable vs member function), this is actually the same:
#include <iostream>

using namespace std;

class Foo {
	public:
		//Must be public
		int bar = 0;

		void setGux(int gux);
		int getGux();
	private: int _gux = 0;
};

void Foo::setGux(int gux) {
	_gux = gux;
}
int Foo::getGux() {
	return _gux;
}

int main() {
	 Foo foo;

	 cout << "Bar: " << endl;
	 cout << foo.bar << endl;
	 foo.bar = 5;
	 cout << foo.bar;

	 cout << "\n\nGux: " << endl;
	 cout << foo.getGux() << endl;
	 foo.setGux(10);
	 cout<< foo.getGux();
	 

	 cin.ignore().get();
	 return 0;
}


When is one preferred above the other?

Also, about using separate headers etc, why ain't this working?
http://s15.postimg.o...mcxmj/image.png
And if I wouldn't be using an IDE, I'd place those files near my executable and include them in the compiler?

Are setters -> mutators, and accessors -> getters complete synonyms; or when do you choose one term over the other?
Was This Post Helpful? 0
  • +
  • -

#4 jimblumberg   User is offline

  • member icon

Reputation: 5570
  • View blog
  • Posts: 17,217
  • Joined: 25-December 09

Re: OOP in C++

Posted 12 February 2016 - 08:11 AM

Quote

Also, about using separate headers etc, why ain't this working?
http://s15.postimg.o...mcxmj/image.png
And if I wouldn't be using an IDE, I'd place those files near my executable and include them in the compiler?

Well it looks like your trying to #include your source file instead of adding it to your project. And remember when you try to #include a file the #include name must match the name of the file.

You also appear to have failed to #include your header file in the Source1.cpp file. You must #include all the required header files in every file that uses the definitions in the header files.

Quote

Are setters -> mutators, and accessors -> getters complete synonyms; or when do you choose one term over the other?

It really depends on the content. C++ programmers often just call the class member functions "class methods". But remember C++ is not java, you really need to try to forget how java does things and concentrate on how you should do it in C++.

Quote

So, about that property-thing (member variable vs member function), this is actually the same:

#include <iostream>

using namespace std;

class Foo {
	public:
		//Must be public
		int bar = 0;   // NOTE 1:

		void setGux(int gux);
		int getGux();
	private: int _gux = 0; // NOTE 2:
};

void Foo::setGux(int gux) {
	_gux = gux; // NOTE 3:
}
int Foo::getGux() {
	return _gux;
}

int main() {
	 Foo foo;

         NOTE 4:
	 cout << "Bar: " << endl;
	 cout << foo.bar << endl;
	 foo.bar = 5;
	 cout << foo.bar;

         NOTE 5:
	 cout << "\n\nGux: " << endl;
	 cout << foo.getGux() << endl;
	 foo.setGux(10);
	 cout<< foo.getGux();
	 
         NOTE 6:
	 cin.ignore().get();
	 return 0;
}



NOTE 1: You should prefer to have your class member variables defined in the private/protected portion of the class to limit access to class members as public member variables break encapsulation.

NOTE 2: First you should strive to have one statement per line and IMO avoid leading and trailing underscores for your variable names. IMO these underscores are easy to miss and easy to use in "reserved" locations. Also this syntax int _gux = 0; is not available in all versions of the C++ standard. It was added in the C++11 version of the standard as a way of initializing the variable in the class body. IMO you should really reserve this to POD (Plain Old Data) and not for C++ classes. And I myself prefer using a constructor instead because a constructor is legal for all the C++ standards.

NOTE 3: See NOTE 2. And realize that you can use a parameter name with the same name as a member variable (not recommended) but you will then need to use the "this" pointer when referring to the member variable.
this->gus = gus;

NOTE 4: See NOTE 1.

NOTE 5: Remember that not all class member variable must be accessible outside of the class. And that you can have accessors that access more than one class member function to provide a "calculated" result. And remember because you're class is using the default (compiler generated) constructor these class member variables are not initialized until you assign a value to them external of the class (also see NOTE 2).

NOTE 6: See NOTE 2. And remember that this line is only needed when you run this program with your IDE. Many other IDE will not require this crutch and if you run the program outside your IDE you also will not require this crutch.


Jim
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1