DOC PREVIEW
WUSTL CSE 332S - C++_classes

This preview shows page 1-2-3-4 out of 13 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 13 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 13 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 13 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 13 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 13 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

From Procedural to Object-oriented ProgrammingFrom C++ Functions to C++ Structs/ClassesUsing Structs and Operators with STL ContainersUsing Structs and Operators with STL AlgorithmsDeclaring and Defining C++ Structs/ClassesStructure of a Simple C++ Class DeclarationConstructorsA Bit More About Default ConstructorsAccess ControlIssues with Encapsulation in C++Friend DeclarationsFriends ExampleOperators let a Struct/Class Work with Entire STLCSE 332: C++ ClassesFrom Procedural to Object-oriented Programming•Procedural programming–Functions have been the main focus so far•Function parameters and return values•Exceptions and how the call stack behaves–We have viewed data and functions as being separate abstractions, for the most part•Object-oriented (a.k.a. OO) programming–Allows us to package data and functions together•Makes data more interesting (adds behavior)•Makes functions more focused (restricts data scope)–This module will start to look at OO programing•Classes/structs, member operators/functions/variables•We’ll cover inheritance, polymorphism, substitution laterCSE 332: C++ Classes From C++ Functions to C++ Structs/Classes•C++ functions encapsulate behavior–Data used/modified by a function must be passed in via parameters–Data produced by a function must be passed out via return type•Classes (and structs) encapsulate related data and behavior–Member variables maintain each object’s sta te–Member functions (methods) and operators have direct access to member variables of the object on which they are called–Class members are private by default, struct members public by default•When to use a struct–Use a struct for things that are mostly about the data–Add constructors and operators to work with STL containers/algorithms•When to use a class–Use a class for things where the behavior is the most important part–Prefer classes when dealing with encapsulation/polymorphism (later)CSE 332: C++ ClassesUsing Structs and Operators with STL Containers#include <vector> // standard template library#include <iostream>using namespace std;#include “point2d.h” // using user-defined code// main function definitionint main (int, char *[]) {vector<Point2D> v; // must give a type here v.push_back(Point2D(2,3)); v.push_back(Point2D(1,4)); for (size_t s = 0; s < v.size(); ++s) { cout << v[s] << endl; // needs Point2D << }return 0;}CSE 332: C++ ClassesUsing Structs and Operators with STL Algorithms // same as before, and add algorithm library#include <vector>#include <algorithm>using namespace std;#include “point2d.h”int main (int, char *[]) {vector<Point2D> v; v.push_back(Point2D(2,3)); v.push_back(Point2D(1,4)); // reorders the points in the vector // note that you don’t give a type here! sort (v.begin(), v.end()); // needs Point2D < return 0;}CSE 332: C++ ClassesDeclaring and Defining C++ Structs/Classes// struct declaration (in point2d.h)struct Point2D { Point2D (int x, int y); bool operator< (const Point2D &) const;int x_;int y_;};// method definitions (in point2d.cpp)Point2D::Point2D (int x, int y) : x_(x), y_(y) {}boolPoint2D::operator< (const Point2D & p2d) const{return (x_ < p2d.x_) || ((x_ == p2d.x_) && (y_ < p2d.y_));}scoping operatorbase class/struct andmember initialization listpromises not to modify object on which it’s calledalso may need ==also may need << (outside struct)CSE 332: C++ ClassesStructure of a Simple C++ Class Declarationclass Date { public: // member functions, visible outside the class Date (); // default constructor Date (const Date &); // copy constructor Date (int d, int m, int y); // another constructor virtual ~Date (); // (virtual) destructor Date & operator= (const Date &); // assignment operator int d () const; int m () const; int y () const; // accessors void d (int); void m (int); void y (int); // mutators string yyyymmdd () const; // generate a formatted string private: // member variables, visible only within functions above int d_; int m_; int y_;};The compiler defines these 4 if you don’t*Don’t forget semicolon at the end of the class declarationoperators can be member functions as well*Compiler omits default constructor if any constructor is declaredCSE 332: C++ ClassesConstructors•A constructor has the same name as its class•Establishes invariants for the class instances (objects)–Properties that always hold–Like, no memory leaks•Passed parameters are used in the base class /member initialization list–You must initialize const and reference members there–Members are constructed in the order they were declared•List should follow that order–Set up invariants before the constructor body is run–Help avoid/fix constructor failure•More on this topic later class Date { public: Date (); Date (const Date &); Date (int d, int m, int y); // ...private: int d_, m_, y_;};// default constructorDate::Date () : d_(0), m_(0), y_(0) {}// copy constructorDate::Date (const Date &d) : d_(d.d_), m_(d.m_), y_(d.y_) {}// another constructorDate::Date (int d, int m, int y) : d_(d), m_(m), y_(y) {}base class / member initialization listconstructor bodyCSE 332: C++ ClassesA Bit More About Default Constructors•Default constructor takes no arguments–Compiler synthesizes one if no constructors are provided•Does default construction of all class members (a.k.a member-wise) –If you write a default constructor•Can initialize default values via base/member list•Must do this for const and reference members•Default construction of built-in types –Default construction does nothing (leaves uninitialized)–It’s an error (as of C++11) to read an uninitialized variableCSE 332: C++ ClassesAccess Control•Declaring access control scopes within a classprivate: visible only within the classprotected: also visible within derived classes (more later)public: visible everywhere –Access control in a class is private by default•but, it’s better style to label access control explicitly•A struct is the same as a class, except –Access control for a struct is public by default–Usually used for things that are “mostly data”•E.g., if initialization and deep copy only, may suggest using a struct–Versus classes, which are expected to have both data and some form of non-trivial behavior•E.g., if reference counting, etc. probably want to use a classCSE 332: C++ ClassesIssues with Encapsulation in C++•Sometimes


View Full Document

WUSTL CSE 332S - C++_classes

Download C++_classes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view C++_classes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view C++_classes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?