Abstract Data Types and C++ Classes

0.0(0)
studied byStudied by 0 people
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/16

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

17 Terms

1
New cards

Abstract Data Type (ADT):

An Abstract Data Type is a high-level description of a data type that emphasizes what a type does rather than how it does it. It defines a set of operations and their semantics, without specifying how these operations are implemented. In simpler terms, an ADT provides a logical blueprint for data types and their operations.

2
New cards

C++ Classes:

In C++, a class is a user-defined data type that encapsulates data and behavior. It allows you to create objects, which are instances of the class. Classes serve as a template for creating objects, defining their properties (attributes) and behaviors (methods). A class defines the abstract data type, and objects of the class represent specific instances of that data type.

3
New cards

C++ Files

when creating a class in C++, you typically organize your code across multiple files: a specification file (header file), an implementation file, and a client/user file

1. Specification File (.h) - MyClass.h

  • The specification file, often denoted with a .h extension, contains the class declaration. It includes the class's member variables and function prototypes (only signatures, no definitions). Here's an example of a simple class declaration:

    // MyClass.h (Specification File)
    #ifndef MYCLASS_H 
    //Include guard to prevent multiple inclusions
    #define MYCLASS_H
    
    class MyClass {
    private:
        int privateVariable;
    
    public:
        MyClass();  // Constructor declaration
        void myFunction();  // Member function declaration
        int getPrivateVariable() const;  // Member function declaration
    };
    
    #endif // End of include guard
    

2. Implementation File (.cpp) - MyClass.cpp(same name as implementation)

  • The specification file, often denoted with a .h extension, contains the class declaration. It includes the class's member variables and function prototypes (only signatures, no definitions). Here's an example of a simple class declaration:

    // MyClass.h (Specification File)
    #ifndef MYCLASS_H  // Include guard to prevent multiple inclusions
    #define MYCLASS_H
    
    class MyClass {
    private:
        int privateVariable;
    
    public:
        MyClass();  // Constructor declaration
        void myFunction();  // Member function declaration
        int getPrivateVariable() const;  // Member function declaration
    };
    
    #endif // End of include guard

3. Client/User File - main.cpp

  • The client file, often named main.cpp, or any other relevant name, uses the class and its functionalities. It includes the specification file to access the class's interface:

    // main.cpp (Client/User File)
    #include <iostream>
    #include "MyClass.h"  // Include the specification file
    
    int main() {
        MyClass obj;  // Create an object of MyClass
    
        obj.myFunction();  // Call member function
        int value = obj.getPrivateVariable();  // Call another member function
        std::cout << "Private Variable: " << value << std::endl;
    
        return 0;
    }
    
  • In this file, you create an object of MyClass and use its member functions.

4
New cards

Class Members

  • Data Members: Variables within a class are known as data members. They represent the attributes or properties of the class.

  • Member Functions (Methods): Functions within a class are called member functions. They define the behavior of the class and operate on the class's data members.

5
New cards

Class Declaration

class ClassName {
private:
    // private data members
public:
    // public data members
    ClassName(); // constructor declaration
    ~ClassName(); // destructor declaration
    void memberFunction(); // member function declaration
};
  • Public: Members declared as public are accessible from outside the class. They can be accessed using objects of the class.

  • Private: Members declared as private are only accessible within the class. They cannot be accessed directly from outside the class.

6
New cards

Encapsulation

Encapsulation is the bundling of data (attributes) and the methods that operate on that data into a single unit known as a class. It hides the internal state of the object from the outside world and restricts access to some of the object's components.

7
New cards

Abstraction

Abstraction is the process of simplifying complex systems by modeling classes appropriate to the problem and working at the most relevant level of inheritance for a particular aspect of the problem. In C++, abstraction is achieved through classes and objects. It allows you to focus on essential qualities of an object while ignoring unnecessary details.

8
New cards

Information Hiding

Information hiding is a key principle of encapsulation. It ensures that the implementation details of a class are hidden from users of the class. Users interact with the class through public methods, abstracting away the internal workings of the class

9
New cards

informal specification of a list ADT that contains integer numbers

TYPE

  • TimeOfDay

Domain

  • Each TimeOfDay value is a time of day in the form of hours, minutes, and seconds

OPERATIONS

  • Create a time object.

  • Print (or write) the time.

  • Return an object containing the time, incremented by one second.

  • Compare two times for equality.

  • Determine if one time is “less than” (comes before) another.

10
New cards

Constructor

An operation that initializes a new instance (variable) of an ADT

11
New cards

Transformer

An operation that changes the value of the ADT; also known as a mutator.

12
New cards

Observer

An operation that allows us to observe the state of an instance of an ADT without changing it; also known as an accessor.

13
New cards

Specification File

// SPECIFICATION FILE (Time0fDay.h)
// This file gives the specification
//of a TimeOfDay abstract data type


class TimeOfDay {
public:
// Constructors
TimeOfDay();
// Post: Initializes hours, minutes, and seconds to 0.

TimeOfDay(int initHours, int initMinutes, int initSeconds);
// Pre: 0 <= initHours <= 23, 0 <= initMinutes <= 59, 0 <= initSeconds <= 59
// Post: Initializes TimeOfDay according to the incoming parameters.

TimeOfDay Increment() const;
// Post: Returns a TimeOfDay instance that is one second later than the current instance.
// If the time is 23:59:59, it wraps around to 00:00:00.

void Write() const;
// Post: Outputs the instance in the format HH:MM:SS.

bool Equal(TimeOfDay otherTime) const;
// Post: Returns true if this instance equals otherTime, false otherwise.

bool LessThan(TimeOfDay& otherTime) const;
// Post: Returns true if this instance comes earlier than otherTime, false otherwise.

private:
int hours; // Hours (0 to 23)
int minutes; // Minutes (0 to 59)
int seconds; // Seconds (0 to 59)
};
14
New cards

The Implementation File (.cpp)

// TimeOfDay.cpp
// This file implements the TimeOfDay member functions
#include "TimeOfDay.h"
#include <iostream>
using namespace std;

TimeOfDay::TimeOfDay() {
// Default constructor: Initialize hours, minutes,and seconds to 0
    hours = 0;
    minutes = 0;
    seconds = 0;
}

TimeOfDay::TimeOfDay(int initHours, int initMinutes, int initSeconds) {
    // Parameterized constructor: Initialize hours, minutes, and seconds with provided values
    hours = initHours;
    minutes = initMinutes;
    seconds = initSeconds;
}


// Increment the TimeOfDay instance and return the updated time
TimeOfDay TimeOfDay::Increment() const {
    // Create a duplicate of the instance
    TimeOfDay result(hours, minutes, seconds);

    // Increment seconds and adjust if necessary
    result.seconds =  result.seconds++;
    if (result.seconds > 59) 
	{
          result.seconds = 0;
          result.minutes = result.minutes++;
             if (result.minutes > 59) 
               {
                 result.minutes = 0;
                 result.hours = result.hours++;
                 if (result.hours > 23) {
                    result.hours = 0; // Adjust if hours carry
            }
        }
    }

    return result; // Return the updated TimeOfDay object
}

// Output the TimeOfDay instance in the format HH:MM:SS
void TimeOfDay::Write() const {
    // Insert extra '0' if hours, minutes, or seconds are single-digit
    if (hours < 10) {
        cout << '0';
    }
    cout << hours << ':';

    if (minutes < 10) {
        cout << '0';
    }
    cout << minutes << ':';

    if (seconds < 10) {
        cout << '0';
    }
    cout << seconds;
}

// Check if the TimeOfDay instance is equal to the given otherTime
bool TimeOfDay::Equal(TimeOfDay otherTime) const {
    return (hours == otherTime.hours &&
            minutes == otherTime.minutes &&
            seconds == otherTime.seconds);
}

// Check if the TimeOfDay instance is less than the given otherTime
bool TimeOfDay::LessThan(TimeOfDay otherTime) const {
    return (hours < otherTime.hours || hours == otherTime.hours 
    && minutes < otherTime.minutes || hours == otherTime.hours 
    && minutes == otherTime.minutes 
    && seconds < otherTime.seconds);
}
  • Member Functions:

    • Definition Format: Member functions are defined outside the class using the ClassName::FunctionName syntax.

    • Accessing Class Members: Member functions can access private data members directly because they are part of the class scope. Private data members are hidden from external code but can be manipulated by member functions.

  • Scope and Member Selection:

    • Class Scope: Member names have class scope, meaning they are bound to the specific class. If the same identifier is declared outside the class, it is unrelated to the class member with the same name.

    • Member Selection Operator (.): Objects access their member functions and variables using the dot (.) operator: object.memberFunction(); or object.memberVariable;.

  • Constructors:

    • Default Constructor: Initializes class data members to default values when an object is created without specific values.

    • Parameterized Constructor: Allows initializing class data members with specific values when an object is created.

  • Member Functions in Classes:

    • Function Parameters: Member functions can have parameters, allowing them to accept external values for processing.

    • Return Types: Member functions can return values or perform operations without returning a value (void functions).

  • Member Function Interaction:

    • Accessing Private Data: Member functions can access private data members of the same class directly, allowing manipulation and validation of data.

    • Class Interactions: Member functions can interact with other member functions and data members within the same class.

  • Object Interactions:

    • Copying Objects: Objects can be copied using assignment operators. When an object is assigned to another, their data members are copied.

    • Comparing Objects: Objects can be compared using member functions. For example, the Equal function compares two objects of the same class for equality.

  • Object Lifecycle:

    • Object Creation: Objects are created when the program execution reaches their declaration statement.

    • Object Destruction: Objects are destroyed when they go out of scope, typically at the end of their block or when delete is explicitly called (for dynamically allocated objects).

15
New cards

client code using TimeOfDay

// A program to create two time objects and manipulate them

#include <iostream>
#include "TimeOfDay.h" // Include the TimeOfDay class header file
using namespace std;

int main() {
// Instantiate two TimeOfDay objects
TimeOfDay timel(5, 30, 0); // timel is set to 05:30:00
TimeOfDay time2; // time2 is initialized to 00:00:00
int loopCount;

// Output the initial times
cout << "timel: ";
timel.Write(); // Output timel: 05:30:00
cout << " time2: ";
time2.Write(); // Output time2: 00:00:00
cout << endl;

// Compare and output whether timel and time2 are equal
if (timel.Equal(time2)) {
cout << "Times are equal" << endl;
} else {
cout << "Times are NOT equal" << endl;
}

// Set time2 equal to timel and output both times
time2 = timel;
cout << "timel: ";
timel.Write(); // Output timel: 05:30:00
cout << " time2: ";
time2.Write(); // Output time2: 05:30:00
cout << endl;

// Compare and output whether timel and time2 are equal after setting them equal
if (timel.Equal(time2)) {
cout << "Times are equal" << endl;
} else {
cout << "Times are NOT equal" << endl;
}

// Increment time2 and output the new time
time2.Increment(); // Increment time2 by one second
cout << "New time2: ";
time2.Write(); // Output the new time2 value
cout << endl;

// Compare timel and time2 and output the result of the comparison
if (timel.LessThan(time2)) {
cout << "timel is less than time2" << endl;
} else {
cout << "timel is NOT less than time2" << endl;
}

// Compare time2 and timel and output the result of the comparison
if (time2.LessThan(timel)) {
cout << "time2 is less than timel" << endl;
} else {
cout << "time2 is NOT less than timel" << endl;
}


// Increment timel and compare it with time2 multiple times, outputting the results
TimeOfDay time(23, 59, 55); // Instantiate a TimeOfDay object near the maximum time
cout << "Incrementing timel from 23:59:55:" << endl;
for (loopCount = 1; loopCount <= 10; loopCount++) {
time.Write();
cout << " ";
time4 = time4. Increment();
// check that it overflows properly
}
cout << endl;
return 0; // End the program
}
<pre><code>// A program to create two time objects and manipulate them

#include &lt;iostream&gt;
#include "TimeOfDay.h" // Include the TimeOfDay class header file
using namespace std;

int main() {
    // Instantiate two TimeOfDay objects
    TimeOfDay timel(5, 30, 0); // timel is set to 05:30:00
    TimeOfDay time2; // time2 is initialized to 00:00:00
    int loopCount;

    // Output the initial times
    cout &lt;&lt; "timel: ";
    timel.Write(); // Output timel: 05:30:00
    cout &lt;&lt; " time2: ";
    time2.Write(); // Output time2: 00:00:00
    cout &lt;&lt; endl;

    // Compare and output whether timel and time2 are equal
    if (timel.Equal(time2)) {
        cout &lt;&lt; "Times are equal" &lt;&lt; endl;
    } else {
        cout &lt;&lt; "Times are NOT equal" &lt;&lt; endl;
    }

    // Set time2 equal to timel and output both times
    time2 = timel;
    cout &lt;&lt; "timel: ";
    timel.Write(); // Output timel: 05:30:00
    cout &lt;&lt; " time2: ";
    time2.Write(); // Output time2: 05:30:00
    cout &lt;&lt; endl;

    // Compare and output whether timel and time2 are equal after setting them equal
    if (timel.Equal(time2)) {
        cout &lt;&lt; "Times are equal" &lt;&lt; endl;
    } else {
        cout &lt;&lt; "Times are NOT equal" &lt;&lt; endl;
    }

    // Increment time2 and output the new time
    time2.Increment(); // Increment time2 by one second
    cout &lt;&lt; "New time2: ";
    time2.Write(); // Output the new time2 value
    cout &lt;&lt; endl;

    // Compare timel and time2 and output the result of the comparison
    if (timel.LessThan(time2)) {
        cout &lt;&lt; "timel is less than time2" &lt;&lt; endl;
    } else {
        cout &lt;&lt; "timel is NOT less than time2" &lt;&lt; endl;
    }

    // Compare time2 and timel and output the result of the comparison
    if (time2.LessThan(timel)) {
        cout &lt;&lt; "time2 is less than timel" &lt;&lt; endl;
    } else {
        cout &lt;&lt; "time2 is NOT less than timel" &lt;&lt; endl;
    }


    // Increment timel and compare it with time2 multiple times, outputting the results
    TimeOfDay time(23, 59, 55); // Instantiate a TimeOfDay object near the maximum time
    cout &lt;&lt; "Incrementing timel from 23:59:55:" &lt;&lt; endl;
    for (loopCount = 1; loopCount &lt;= 10; loopCount++) {
        time.Write();
        cout &lt;&lt; "  ";
        time4 = time4. Increment(); 
        // check that it overflows properly
    }
    cout &lt;&lt; endl;
    return 0; // End the program
}
</code></pre>
16
New cards

Object Instantiation

Objects are instances of classes. When a class is instantiated, memory is allocated to store its data members. Each object has its own set of data members.

17
New cards