Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

declare class c++

#include <iostream>
#include <string>

class Shirt
{ // Private attributes access
  
// Attributes under this line can be accessed only inside of the class.
// (In the block of code with curly brackets marked with
// "Private attributes access")
private: // this line is not necessary, because fields declared
         // before any access specifier are private by default
  
    // Class field
    std::string purchaseDate;
  
// Attributes under this line can be accessed everywhere
public:
    // Class field
    unsigned int sleeveLength;
    // Class Method
    void shortenSleeve(unsigned int n)
    {
        if (sleeveLength - n < 0)
        {
            std::cout << "Cannot shorten that much" << std::endl;
            return;
        }
        sleeveLength -= n;
        std::cout << "Sleeve Shortened successfully" << std::endl;
    }
  
    // Constructor
    Shirt(std::string purchD, int sL) : purchaseDate(purchD), sleeveLength(sL)
    {
    }

    /* Alternative
    Shirt(std::string purchD, int sL)
    {
        purchaseDate = purchD;
        sleeveLength = sL;
    }
    */
  
}; // Private attributes access

int main()
{
    Shirt JoesShirt("07.07.2022", 70);
    // Alternative
    // Shirt JoesShirt = Shirt("07.07.2022", 70);
  
  	// std::cout << JoesShirt.purchaseDate // Error
    JoesShirt.shortenSleeve(20);
    std::cout << JoesShirt.sleeveLength << std::endl;
}

/*
Output:
    Sleeve Shortened successfully
    50
*/
Source by cplusplus.com #
 
PREVIOUS NEXT
Tagged: #declare #class
ADD COMMENT
Topic
Name
6+9 =