Thread: Please help with beginner object oriented programming!

  1. #1
    Registered User
    Join Date
    Aug 2014
    Posts
    20

    Lightbulb Please help with beginner object oriented programming!

    Hi everyone,

    I'm new to C++/Object Oriented Programming and would like some guidance. I am currently working on a program that will solve physics problems using the kinematic equations.

    I'm having issues sorting out the OOP part. i currently have acceleration, velocity, displacement, and time in their own individual classes. i also have a kinematics class which is where i thought i'd put the equations that will perform the calculations and return unknown variable(s). I'm not sure if this is how OOP works though.

    As far as i know, OOP focus is on data and operations on the data. In the past i had a class and member functions that operate on that piece of data. now I'm not sure how to write my program :/
    I was also thinking that maybe i could list my equations as friend functions.

    (FORGIVE MY IGNORANCE, THIS IS MY FIRST MONTH WITH C++,OOP).

    here are some snippets of header files to give everyone an idea of what i had in mind.


    Code:
    #ifndef Velocity_hpp
    
    #define Velocity_hpp
    
    
       #include <iostream>
       using namespace std;
    
    
       class Velocity
       {
          double velocity;
          
       public:
          //constructors
          Velocity();
          Velocity(double v);
          
          //deconstructor
          ~Velocity();
          
          //mutator functions
          void setVelocity(double v);
          
          //accessor functions
          double getVelocity();
          
          //friend
          friend ostream& operator<<(ostream& out_stream, const Velocity &velocity);
       };
    
    
    #endif
    Code:
    
    #ifndef Time_hpp
    
    
    #define Time_hpp
    
    
       #include <iostream>
       using namespace std;
    
    
       class Time
       {
          double time;
       
       public:
          //constructors
          Time();
          Time(double t);
       
          //deconstructor
          ~Time();
       
          //mutator functions
          void setTime(double t);
       
          //accessor functions
          double getTime();
       
          //friend
          friend ostream& operator<<(ostream& out_stream, const Time &time);
       };
    
    
    #endif
    Code:
    
    #ifndef Displacement_hpp
    
    
    #define Displacement_hpp
    
    
       #include <iostream>
       using namespace std;
    
    
       class Displacement
       {
          double displacement;
          
       public:
          //constructors
          Displacement();
          Displacement(double s);
          
          //deconstructor
          ~Displacement();
          
          //mutator functions
          void setDisplacement(double s);
          
          //accessor functions
          double getDisplacement();
          
          //friend
          friend ostream& operator<<(ostream& out_stream, const Displacement &displacement);
       };
    
    
    #endif
    Code:
       
    #ifndef Acceleration_hpp
    
    
    #define Acceleration_hpp
    
    
       #include <iostream>
       using namespace std;
    
    
       class Acceleration
       {
          double acceleration;
          static const double gravity = 9.83;
          
       public:
          //constructors
          Acceleration();
          Acceleration(double a);
          
          //deconstructor
          ~Acceleration();
          
          //mutator functions
          void setAcceleration(double a);
          
          //accessor functions
          double getAcceleration();
          double getGravity();
          
          //friend
          friend ostream& operator<<(ostream& out_stream, const Acceleration &acceleration);
       };
    
    
    #endif
    Code:
    #ifndef Kinematics_hpp
    
    
    #define Kinematics_hpp
    
    
       #include <iostream>
       #include "mainprj.hpp"
       #include "Acceleration.hpp"
       #include "Displacement.hpp"
       #include "Kinematics.hpp"
       #include "Time.hpp"
       using namespace std;
    
    
    #endif

    as you can see i have no functions in my kinematics class yet.. this is because I'm not so sure this is how i should implement my program. some requirements for this program are that it must be OOP, have function overrides, overloads, and other C++ material that could not be done in C.

    ANY HELP/ADVICE WOULD BE GREATLY APPRECIATED.
    Last edited by allen.; 04-25-2015 at 04:55 PM.

  2. #2
    Guest
    Guest
    I'm not well versed in OOP, but do the Velocity, Acceleration and Displacement classed represent properties or do you actually want to implement computational (self-)effects inside them?

    If the former, then instead of building separate classes, I would suggest a single lightweight "dumb" one for the physical objects, along with the Kinematics class you mentioned. The latter could then cycle over an array of these objects and use its various methods to update their properties.

  3. #3
    Registered User
    Join Date
    Aug 2014
    Posts
    20

    Thumbs up Thanks for the reply!

    Quote Originally Posted by Guest View Post
    I'm not well versed in OOP, but do the Velocity, Acceleration and Displacement classed represent properties or do you actually want to implement computational (self-)effects inside them?

    If the former, then instead of building separate classes, I would suggest a single lightweight "dumb" one for the physical objects, along with the Kinematics class you mentioned. The latter could then cycle over an array of these objects and use its various methods to update their properties.
    Hi Adrian! Thanks for the response.

    As of right now, these classes represent data and inside the classes i do not wish to perform any calculations or manipulations on this data.

    My intention was to make these classes to encapsulate the data. In my main i will get the user to enter the problem, then i will use helper functions in main to extract the known variables (Acceleration, Displacement, etc.) from the problem and pass this off to my Kinematics class (which will be a class of overloaded functions) which will perform the needed calculations to find the unknown(s).

    So you think I'm on the right track by having a Kinematics class? this class will have no data but functions that will compute other variables.

    Also, can you elaborate a bit on one "dumb" class? are you saying maybe i should place all data (time, velocity, displacement, acceleration) in one class?

    Please help because i was already troubled when i had to make my acceleration and velocity classes by themselves. i wanted to use inheritance since velocity is a measurement of displacement/time and so on. I did some research on multiple inheritance to see if i could implement them using that method but i kept reading that under no circumstance should multiple inheritance be used. That's strange because if something is so bad, why is it part of the language? but that's a question for another thread.

    Once again, Thanks for the response! any help is appreciated!

  4. #4
    Guest
    Guest
    Quote Originally Posted by allen. View Post
    (...) In my main i will get the user to enter the problem, then i will use helper functions in main to extract the known variables (Acceleration, Displacement, etc.) from the problem and pass this off to my Kinematics class (which will be a class of overloaded functions) which will perform the needed calculations to find the unknown(s).
    I see. I misinterpreted your goal as doing computations on many objects at once, but from what you wrote, only one problem (one set of variables) is to be solved, correct?

    Quote Originally Posted by allen. View Post
    So you think I'm on the right track by having a Kinematics class? this class will have no data but functions that will compute other variables.
    Yes, that class seems sensible to me. It was the other classes that I had doubts about.

    Quote Originally Posted by allen. View Post
    Also, can you elaborate a bit on one "dumb" class? are you saying maybe i should place all data (time, velocity, displacement, acceleration) in one class?
    The way I understand OOP, encapsulating your data only makes sense if the functions that modify the data are bundled along with it, i.e. the object should be mostly self-contained and self-modifying. Admittedly, I know too little about the nature of your program, but if e.g. velocity is just a parameter, then you should store it like you would any regular variable.

    By "dumb" I meant a POD type - basically just a structure holding data that doesn't do anything on its own. When using lots of objects, this can be more efficient than using "smart" self-contained classes, but it's also antithetical to the ideas behind OOP. If your program only tracks one object at a time, it really shouldn't matter and readability is more important.

    Quote Originally Posted by allen. View Post
    Please help because i was already troubled when i had to make my acceleration and velocity classes by themselves. i wanted to use inheritance since velocity is a measurement of displacement/time and so on.
    If I understood the rationale behind the program better, I might be able to give a suggestion.

    Quote Originally Posted by allen. View Post
    I did some research on multiple inheritance to see if i could implement them using that method but i kept reading that under no circumstance should multiple inheritance be used. That's strange because if something is so bad, why is it part of the language? but that's a question for another thread.
    I think (multiple) inheritance pays off with really large and complex projects, like when you write CAD software for Airbus or stuff like that. So it's a strict philosophy, enforced by language features, that promises a decrease in software bugs (and possibly an increase in productivity). I only write tiny programs, so I never use it. The good thing about C++ is that you can take what you need, and leave the rest; this is not an accident/loophole.

    If you can give some more details (or an example) of what you program does, I think I can be more specific in my suggestions; or at least realize whether this is too hard for me :P
    Last edited by Guest; 04-25-2015 at 07:17 PM.

  5. #5
    Registered User
    Join Date
    Nov 2014
    Posts
    6

    Response

    I suggest you finish off your class like this and then create objects and make function implementations on them in a main.cpp

    Code:
    //kinematics.hpp kinematics class
    
    
    
    
    #ifndef Kinematics_hpp
     
     
    #define Kinematics_hpp
     
     
       #include <iostream>
       #include "mainprj.hpp"
       #include "velocity.hpp"
       #include "Acceleration.hpp"
       #include "Displacement.hpp"
       #include "Kinematics.hpp"
       #include "Time.hpp"
       using namespace std;
    
    
    
    
       class kinematics
       {
           velocity vel;
           acceleration acc;
           time t_time;
           displacement dis;
       public:
           kinematics(velocity V,acceleration A,displacement S,Time T);
           kinematics(); // constructor
           ~kinematics(); //deconstructor
    
    
           // calculation formulas
           double calculateVelocity(displacement S,time T);
           double calculateDisplacement(velocity V,time T);
           double calculateAcceleration(velocity V0,velocity V1,time T0,time T1);
           //overloading fuctions
           friend ostream &operator<<(ostream &,const kinematics &);
           friend istream &operator>>(istream & ,const kinematics &);
    
    
       };
    
    
     
    #endif
    
    
       //kinematics.cpp  implementation details
    
    
    #include "kinematics.hpp"
    
    
       kinematics::kinematics(velocity V,acceleration A,displacement S,Time T)
       {
           vel=V;
           acc=A;
           dis=S;
           t_time=T;
       }
    
    
    
    
    
    
       kinematics::calculateVelocity(displacement S,time T)
       {
           velocitiy V=0;
           V=S/T;
           return V;
       }
    
    
       kinematics::calculateAcceleration(velocity V0,velocity V1,time T0,time T1)
       {
           Acceleration a=0;
           a=(V1-V0)/(T1-T0);
           return a;
       }
    
    
       kinematics::calculateDisplacement(velocity V,time T)
       {
           displacement S=0;
           s=v*t;
           return s;
       }
    
    
       istream &operator>>(istream &in,kinematics k)
       {
           do sth here ;
           ...
           return in;
       }
    
    
       ostream &operator<<(ostream &out,kinematics k)
       {
           do sth here;
           ...
           return out;
       }

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Guest View Post
    The way I understand OOP, encapsulating your data only makes sense if the functions that modify the data are bundled along with it, i.e. the object should be mostly self-contained and self-modifying. Admittedly, I know too little about the nature of your program, but if e.g. velocity is just a parameter, then you should store it like you would any regular variable.

    By "dumb" I meant a POD type - basically just a structure holding data that doesn't do anything on its own. When using lots of objects, this can be more efficient than using "smart" self-contained classes, but it's also antithetical to the ideas behind OOP. If your program only tracks one object at a time, it really shouldn't matter and readability is more important.
    Well, that's not strictly true. I would it more as a way of saying that a class offers services for some kind of data. But there's an added benefit of encapsulating something in a class, and that is that it's a separate type. If velocity, acceleration, etc are all doubles or ints, then you can interchange them freely, which may cause bugs (e.g. you pass an acceleration variable instead of velocity). By encapsulating them, you are guaranteed a compile error.

    Still, bundling together state and functions that need to modify that state makes sense. Mostly it makes sense if this state persists between function calls. In C, for such functions, you'd basically have to pass in an argument to modify. In C++, that would be the this pointer.

    But yeah, the main idea behind OOP is that your put highly coupled data and functions that modify said data together in a class and then hide this data from the outside world. Then you make controlled functions to modify and get the data. That gives you stronger guarantees to ensure the data is correct and protects the outside world from changes to the data.

    I think (multiple) inheritance pays off with really large and complex projects, like when you write CAD software for Airbus or stuff like that. So it's a strict philosophy, enforced by language features, that promises a decrease in software bugs (and possibly an increase in productivity). I only write tiny programs, so I never use it. The good thing about C++ is that you can take what you need, and leave the rest; this is not an accident/loophole.
    Multiple inheritance can be tricky, but even so, it makes sense in a couple of situations, even basic ones. Don't assume it's evil because some languages don't support it (*cough* java *cough*). It can yield some surprises, though, which may be why it's a little tricky to use.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  7. #7
    Registered User
    Join Date
    Aug 2014
    Posts
    20

    Lightbulb Here's some more info! hopefully it helps

    Quote Originally Posted by Guest View Post
    I see. I misinterpreted your goal as doing computations on many objects at once, but from what you wrote, only one problem (one set of variables) is to be solved, correct?


    Yes, that class seems sensible to me. It was the other classes that I had doubts about.


    The way I understand OOP, encapsulating your data only makes sense if the functions that modify the data are bundled along with it, i.e. the object should be mostly self-contained and self-modifying. Admittedly, I know too little about the nature of your program, but if e.g. velocity is just a parameter, then you should store it like you would any regular variable.

    By "dumb" I meant a POD type - basically just a structure holding data that doesn't do anything on its own. When using lots of objects, this can be more efficient than using "smart" self-contained classes, but it's also antithetical to the ideas behind OOP. If your program only tracks one object at a time, it really shouldn't matter and readability is more important.

    Hey Adrian, thanks for the reply!

    Yes i agree that I could do the program using a basic "Dumb" structure, but the program requirements are that it must be OOP and incorporate C++ material.



    Quote Originally Posted by Guest View Post
    If I understood the rationale behind the program better, I might be able to give a suggestion.



    If you can give some more details (or an example) of what you program does, I think I can be more specific in my suggestions; or at least realize whether this is too hard for me :P
    So here's the whole idea- Physics problems suck.

    Initially i wanted the user to be able to copy/paste the entire word problem and i would extract the knowns/unknowns (very difficult). this will be very time consuming. Because i have less than two weeks to do this (as well as studying for finals and two other projects) i will have to write a program that will have the user: (in this order)

    1) Select the type of problem (constant acceleration, free fall, uniform motion, etc.)

    2) from there, tell me the unknown variable(s) (initial velocity, final velocity, final position, average acceration, etc.) and i will create instances of these variables (using the default constructor).

    3) tell me the known variables, and i will create instances of these variables as well (using the single arg constructor)

    from there i will pass all variables (known and unknown) over to the suitable kinematic function that will solve for unknown(s). and print the answer to console.

    this actually simplifies my program a great deal because i won't have to write anything that will "do the thinking" for the user.

    hopefully i'll be able to complete my original program purpose this summer when i have more time, but for now i just want a working program that incorporates a bunch of C++ stuff

    If you (OR ANYONE ELSE) have a better way of constructing the OOP portion, i am open for suggestions. I'm trying to learn as much about it as possible.
    Last edited by allen.; 04-26-2015 at 10:54 AM.

  8. #8
    Registered User
    Join Date
    Aug 2014
    Posts
    20
    Can someone please help me with this compile error?

    Kinematics.cpp: In function ‘double calculateDisplacement(Acceleration, Time)’:
    Kinematics.cpp:12:20: error: no match for ‘operator*’ (operand types are ‘Velocity()’ and ‘Time’)
    return (vInitial*t)+(0.5*(a*(t*t)))
    ^



    it seems to me that it doesnt recognize multiplication.

  9. #9
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Seems pretty obvious to me. You are trying to multiple a Velocity and a Time. Velocity and Time are classes or different types. The compiler does not magically know how to multiply two different user-defined types.
    Solutions: Either use a getter to get the "real" time or velocity as a double or int, then multiply them or overload operator * which takes a Velocity and Time, e.g.:

    Code:
    double operator * (const Velocity& v, const Time& r)
    {
    // Do stuff
    }
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  10. #10
    Registered User
    Join Date
    Aug 2014
    Posts
    20

    Thanks for the reply! Now another compile error...

    Quote Originally Posted by Elysia View Post
    Seems pretty obvious to me. You are trying to multiple a Velocity and a Time. Velocity and Time are classes or different types. The compiler does not magically know how to multiply two different user-defined types.
    Solutions: Either use a getter to get the "real" time or velocity as a double or int, then multiply them or overload operator * which takes a Velocity and Time, e.g.:

    Code:
    double operator * (const Velocity& v, const Time& r)
    {
    // Do stuff
    }
    Thanks for the quick reply!

    Like i said in my initial post, please forgive my ignorance, I'm just trying to learn the language and the concepts of OOP.

    i figured that part out, i used my accessor functions to return the double value. but now i have my Kinematics class that has static functions. I made them static because they can be called by class name. but now when i compile i get :

    g++ -g -Wall -o mainprj mainprj.cpp Velocity.o Time.o Displacement.o Acceleration.o Kinematics.o
    mainprj.cpp: In function ‘void constantAcceleration()’:
    mainprj.cpp:142:33: error: ‘Kinematics’ was not declared in this scope
    distanceTraveled(Kinematics.calculateDisplacement( constantAcceleration, timeElapsed));
    ^
    mainprj.cpp:148:33: error: ‘Kinematics’ was not declared in this scope
    distanceTraveled(Kinematics.calculateDisplacement( constantAcceleration, timeElapsed,initialVelocity));


    How do i get main to recognize Kinematics when its just a list of functions and no instance

  11. #11
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    You have to use

    Kinematics::calculateDisplacement

    The dot operator can only be used for instances of objects. For types, you must use the "::" operator.
    But I also question the usage of static functions here. If it's static, then you have to question whether it belongs in a class in the first place. Why is it static? What is the class's role in this? What functionality does the class have?
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  12. #12
    Registered User
    Join Date
    Aug 2014
    Posts
    20
    Quote Originally Posted by Elysia View Post
    You have to use

    Kinematics::calculateDisplacement

    The dot operator can only be used for instances of objects. For types, you must use the "::" operator.
    But I also question the usage of static functions here. If it's static, then you have to question whether it belongs in a class in the first place. Why is it static? What is the class's role in this? What functionality does the class have?

    good question that was my original question on this thread. I'm not sure if what I'm doing is correct. I will refrain from bashing on my professor but he/she is attempting to introduce C++/OOP at the end of the semester, so under the time constraints many things will be left out. The concept of OOP is very fresh to me so I'm struggling with the basics. The majority of the course was python programming.

    But my idea was to have 5 classes, Velocity, Acceleration, Time, Displacement. then there was the question about where i should place all of the variations of the kinematic equations to perform the calculations. I also questioned if it was appropriate to place this in a class of its own, that's why I posted this question. There is no data, only functions... If not in a class, where would be the most appropriate place to have these functions?

    to be blunt:
    Why is it static? because there are no Kinematics objects
    What is the class's role in this? to calculate values. these values will be stored as other objects (velocity, time, etc.)
    What functionality does the class have? ??? i guess its just a container for functions.
    Last edited by allen.; 04-26-2015 at 04:55 PM.

  13. #13
    Registered User
    Join Date
    Aug 2014
    Posts
    20
    I figured it out. thanks for pushing me in the right direction!

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    If some abstraction has no state, then a class is not suitable for that abstraction. If you're just looking for grouping some function together that works on some data, then you should consider using namespaces.

    The reason I haven't given some advice on the structure is because I don't understand the full picture of what is in the system, what it's supposed to do and the various components of it. So that's what you have to think about. Break down the various components of a system into small parts that describe what they do, what state they need, if any, and how they interact with each other. From that base, you can decide what should be modeled as what. This is the basics of object-oriented programming.

    What are your requirements? What do you want the system to do?

    To be honest, slapping OOP on something as small as just calculating some physics usually is overkill because you have to overthink to get it into place. It falls more easily into place as you build a larger system. For example, you may have some algorithm that works on some data. But it might not matter where the data comes from, only that it's in a specific format. But you may want to do other processing on said data afterwards, so it makes sense to model these kinds of data as some classes with operations. The algorithm would take a reference to a base class which has some interface that allows the algorithm to work with the data and produce some result.

    Sounds abstract? Don't worry. Such things fall into place when you actually design a system that would benefit from these kinds of things.

    OOP is not easy. It's something you have to learn gradually over a long period of time. Don't beat yourself up if you can't grasp it right now.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Elysia
    If some abstraction has no state, then a class is not suitable for that abstraction.
    This is not necessarily true though, e.g., exception classes and function objects do not necessarily need state. If you consider those two examples contrived because exception classes typically have the error message as state, and function objects that do not need state could just be functions, consider also visitor classes in an implementation of the visitor pattern: they do not necessarily need state, but having them as subclasses is part of making use of single dispatch virtual calls to implement double dispatch.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [help] Object-Oriented Programming
    By null321 in forum C++ Programming
    Replies: 4
    Last Post: 08-02-2009, 12:29 PM
  2. What is Object Oriented Programming?
    By sunrising in forum C++ Programming
    Replies: 6
    Last Post: 04-23-2008, 07:58 AM
  3. Object Oriented Programming
    By obaid in forum C++ Programming
    Replies: 5
    Last Post: 08-22-2007, 05:31 AM
  4. object oriented programming
    By l2u in forum C++ Programming
    Replies: 10
    Last Post: 11-06-2006, 10:18 AM
  5. Object Oriented Programming
    By eric123 in forum C++ Programming
    Replies: 6
    Last Post: 11-30-2005, 04:56 AM

Tags for this Thread